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 | 19x 15x 15x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x | 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,
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.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,
alternatives = [],
manuallyModified = false,
cascadedFrom = [],
sessionId,
abortSignal
}: {
subjectId: string;
metadataId: string;
type?: Type;
value: RuntimeValue<Type>;
manuallyModified?: boolean;
confidence?: number;
db: DatabaseHandle;
alternatives?: Array<{ value: RuntimeValue<Type>; confidence: number }>;
cascadedFrom?: string[];
abortSignal?: AbortSignal | undefined;
sessionId?: string | undefined;
}) {
Iif (!namespaceOfMetadataId(metadataId)) {
throw new Error(`Le metadataId ${metadataId} n'est pas namespacé`);
}
Iif (confidence > 1) {
console.warn(`Confidence ${confidence} is greater than 1, capping to 1`);
confidence = 1;
}
abortSignal?.throwIfAborted();
const newValue = {
value: serializeMetadataValue(value),
confidence,
manuallyModified,
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);
Iif (!metadata) throw new Error(`Métadonnée inconnue avec l'ID ${metadataId}`);
Iif (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();
Iif (session) {
if (session.metadata) {
session.metadata[metadataId] = newValue;
} else {
session.metadata = { [metadataId]: newValue };
}
db.put('Session', session);
} else if (image) {
image.metadata[metadataId] = newValue;
db.put('Image', image);
E} else if (observation) {
observation.metadataOverrides[metadataId] = newValue;
db.put('Observation', observation);
} else if (imagesFromImageFile) {
for (const { id } of imagesFromImageFile) {
await storeMetadataValue({
db,
sessionId,
subjectId: id,
metadataId,
value,
confidence,
manuallyModified,
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();
if (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);
if (!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,
cascadedFrom: [...cascadedFrom, metadataId],
abortSignal,
...cascade
});
}
// Only refresh table state once everything has been cascaded, meaning not inside recursive calls
Eif (cascadedFrom.length === 0 && sessionId) {
await refreshTables(sessionId, image ? 'Image' : 'Observation');
}
}
/**
*
* @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
});
}
}
} 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;
}
|