forked from mtusi2026/mtusi2026lab7
Prepare verified laboratory 7 implementation and evidence
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
import {resolve} from 'node:path';
|
||||
const workspace=resolve(import.meta.dir,'..'),root=resolve(workspace,'lab5');const results=[];
|
||||
for(const workers of [1,2,4]){const gate=Bun.spawnSync(['game-running'],{stdout:'pipe',stderr:'pipe'});if(gate.exitCode!==1){console.log(JSON.stringify({benchmarkSkipped:true,gateExit:gate.exitCode,completedProfiles:results.length}));process.exit(0)};console.log(JSON.stringify({gameRunningExit:1,concurrency:workers,cpuLimit:1,memoryLimit:'2GiB',sampling:'2seconds, one run; per-attempt p95 and per-process VmHWM'}));const r=Bun.spawnSync([resolve(root,'scripts/compose.sh'),'run','--rm','--no-deps','--entrypoint','/argon-bench.test','-v',resolve(workspace,'lab7-argon-bench.test')+':/argon-bench.test:ro','-e','KDF_CONCURRENCY='+workers,'worker','-test.run','^$','-test.bench','^BenchmarkArgonLogin$','-test.benchtime=2s','-test.count=1'],{cwd:root,stdout:'pipe',stderr:'pipe'});const out=new TextDecoder().decode(r.stdout);console.log(out);if(r.exitCode!==0){console.error(new TextDecoder().decode(r.stderr));throw new Error('Argon benchmark failed')};results.push({workers,exit:r.exitCode})};console.log(JSON.stringify({allProfilesPassed:true,profiles:results}));
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"checkedAt": "2026-11-16T04:36:58.403Z",
|
||||
"wire": [
|
||||
{
|
||||
"phase": "cold",
|
||||
"path": "/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:bg4fowucaheyoa",
|
||||
"method": "GET",
|
||||
"status": 404,
|
||||
"contentType": "application/json",
|
||||
"bytes": 365
|
||||
},
|
||||
{
|
||||
"phase": "cold",
|
||||
"path": "/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:bg4fowucaheyoa",
|
||||
"method": "GET",
|
||||
"status": 404,
|
||||
"contentType": "application/json",
|
||||
"bytes": 365
|
||||
},
|
||||
{
|
||||
"phase": "cold",
|
||||
"path": "/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/",
|
||||
"method": "POST",
|
||||
"status": 201,
|
||||
"contentType": "application/json",
|
||||
"bytes": 1440
|
||||
},
|
||||
{
|
||||
"phase": "reload",
|
||||
"path": "/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:bg4fowucaheyoa",
|
||||
"method": "GET",
|
||||
"status": 200,
|
||||
"contentType": "application/json",
|
||||
"bytes": 1440
|
||||
}
|
||||
],
|
||||
"issues": [
|
||||
{
|
||||
"phase": "cold",
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 404 (Not Found)"
|
||||
},
|
||||
{
|
||||
"phase": "cold",
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 404 (Not Found)"
|
||||
}
|
||||
],
|
||||
"source": "actual shipped pageHistorySrv/userStorage delivered sourcemap; GET404 is missing resource, not storage failure",
|
||||
"normalUIWrite": true,
|
||||
"readAfterPersist": true,
|
||||
"unexpectedReloadIssues": 0
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
import { type Location } from 'history';
|
||||
import { throttle } from 'lodash';
|
||||
import { distinctUntilChanged } from 'rxjs';
|
||||
import * as z from 'zod';
|
||||
|
||||
import { type NavModelItem } from '@grafana/data';
|
||||
import { locationService } from '@grafana/runtime';
|
||||
import { UserStorage } from '@grafana/runtime/internal';
|
||||
import { type AppChromeService, getPageTitle } from 'app/core/components/AppChrome/AppChromeService';
|
||||
import { isUrlRewrite } from 'app/core/navigation/urlRewrite';
|
||||
import impressionSrv from 'app/core/services/impression_srv';
|
||||
import { parseJsonWithSchema } from 'app/core/utils/parseJsonWithSchema';
|
||||
import { isRenderTarget } from 'app/features/dashboard/services/isRenderTarget';
|
||||
|
||||
import { classifyPage, recordableSearch } from './classifyPage';
|
||||
import { hasNothingToResume } from './hasNothingToResume';
|
||||
import {
|
||||
clearHistory,
|
||||
EMPTY_HISTORY,
|
||||
fitsEntryCap,
|
||||
type HistorySnapshot,
|
||||
type HistoryState,
|
||||
mergeStored,
|
||||
PAGE_HISTORY_MAX_PER_KIND,
|
||||
recordTitle,
|
||||
recordVisit,
|
||||
toStored,
|
||||
} from './pageHistoryState';
|
||||
import { type PageHistoryEntry } from './types';
|
||||
|
||||
const STORAGE_SERVICE = 'grafana-page-history';
|
||||
/** One envelope per user; the user-storage namespace already separates orgs. */
|
||||
const STORAGE_KEY = 'history';
|
||||
/** Ordinary URL changes coalesce into one write per window; hiding the tab and `clear()` write at once. */
|
||||
export const PAGE_HISTORY_PERSIST_MS = 30_000;
|
||||
/** JS `Date` range; larger values are not instants. */
|
||||
const MAX_EPOCH_MS = 8.64e15;
|
||||
|
||||
/** Persisted row. The page identity is derived from the pathname on load, so a rule change reclassifies old rows. */
|
||||
const StoredEntrySchema = z.object({
|
||||
pathname: z
|
||||
.string()
|
||||
.startsWith('/')
|
||||
.refine((pathname) => !pathname.startsWith('//')),
|
||||
search: z.string().refine((search) => search === '' || search.startsWith('?')),
|
||||
lastVisited: z.number().int().min(0).max(MAX_EPOCH_MS).optional(),
|
||||
title: z.string().optional(),
|
||||
});
|
||||
|
||||
/** Everything stored under the key. `clearedAt` is the epoch ms of the last clear, 0 when never cleared. */
|
||||
const StoredSchema = z.object({
|
||||
clearedAt: z.number().int().min(0).max(MAX_EPOCH_MS),
|
||||
entries: z.array(z.unknown()),
|
||||
});
|
||||
|
||||
/**
|
||||
* Validates the stored copy row by row so one bad or oversized entry drops only itself. Rows that no longer
|
||||
* classify are dropped. Anything but the envelope loads as empty.
|
||||
*/
|
||||
function parseStored(raw: string | null): HistorySnapshot {
|
||||
const { clearedAt, entries: rows } = parseJsonWithSchema(raw, StoredSchema, { clearedAt: 0, entries: [] });
|
||||
const entries: PageHistoryEntry[] = [];
|
||||
for (const row of rows) {
|
||||
const result = StoredEntrySchema.safeParse(row);
|
||||
if (!result.success || !fitsEntryCap(result.data)) {
|
||||
continue;
|
||||
}
|
||||
const page = classifyPage(result.data.pathname, result.data.search);
|
||||
if (page) {
|
||||
entries.push({ ...result.data, ...page });
|
||||
}
|
||||
}
|
||||
return { clearedAt, entries };
|
||||
}
|
||||
|
||||
function serialize({ clearedAt, entries }: HistoryState): string {
|
||||
return JSON.stringify({ clearedAt, entries: entries.map(toStored) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the pages the user visits (with their URL state) so the homepage can link back to them.
|
||||
* One envelope per user and org in `UserStorage`. Every write merges with the stored copy under a version check,
|
||||
* so tabs and browsers converge; localStorage is used only for signed-out users and is not a fallback for
|
||||
* failed requests. The merge rules live in `pageHistoryState`; this class wires events and storage to them.
|
||||
*
|
||||
* Request policy: ordinary URL changes coalesce into one write at most every `PAGE_HISTORY_PERSIST_MS` per tab;
|
||||
* hiding the tab and `clear()` write immediately; every `getEntries()` and the startup load each cost one read.
|
||||
* A write is one read plus one write, plus one more pair per version conflict. A failed write is retried by the
|
||||
* next change or tab hide, never on a timer. Overlapping operations in one tab serialize on `UserStorage`'s
|
||||
* lock; a change made while a write is in flight is picked up by the next one. The write on tab hide is a plain
|
||||
* request, so closing the tab can lose the changes of the current window.
|
||||
*/
|
||||
export class PageHistorySrv {
|
||||
private state = EMPTY_HISTORY;
|
||||
/** Memory holds a change that storage has not confirmed. */
|
||||
private dirty = false;
|
||||
private readonly storage = new UserStorage(STORAGE_SERVICE);
|
||||
private ready: Promise<void> | undefined;
|
||||
/**
|
||||
* Changes made before the stored copy is in, replayed in order once it is. A visit that only refreshes a
|
||||
* page's row (a menu destination, a rewrite) has to see the stored row, or it finds none and changes nothing.
|
||||
*/
|
||||
private pending: Array<() => void> | undefined = [];
|
||||
/** The menu as it is now, read per visit: items come and go with permissions, plugins and bookmarks. */
|
||||
private navTree: () => NavModelItem[] = () => [];
|
||||
|
||||
private readonly scheduleWrite = throttle(() => this.write(), PAGE_HISTORY_PERSIST_MS, {
|
||||
leading: false,
|
||||
trailing: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* Starts recording. `navTree` is read on every visit to tell menu destinations from pages worth a row. Returns a
|
||||
* function that stops recording and drops any pending write. Renderer sessions record nothing.
|
||||
*/
|
||||
start(chrome: AppChromeService, navTree: () => NavModelItem[]): () => void {
|
||||
// Image-renderer and report captures load pages as the user; their visits are not the user's.
|
||||
if (isRenderTarget()) {
|
||||
return () => {};
|
||||
}
|
||||
this.ready = this.load();
|
||||
this.navTree = navTree;
|
||||
|
||||
// `history.listen` never emits the landing page.
|
||||
this.apply(locationService.getLocation(), false);
|
||||
|
||||
const unlisten = locationService
|
||||
.getHistory()
|
||||
.listen((location, action) => this.apply(location, action === 'REPLACE' && isUrlRewrite(location.state)));
|
||||
// Pages set their nav after they render, so the title arrives after the navigation was recorded. Only a nav
|
||||
// change is a page setting its nav; other chrome updates keep the previous page's nav objects.
|
||||
const chromeSubscription = chrome.state
|
||||
.pipe(distinctUntilChanged((a, b) => a.sectionNav === b.sectionNav && a.pageNav === b.pageNav))
|
||||
.subscribe((state) => this.setTitle(getPageTitle(state)));
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === 'hidden' && this.dirty) {
|
||||
void this.writeNow();
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
|
||||
return () => {
|
||||
unlisten();
|
||||
chromeSubscription.unsubscribe();
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
this.pending = undefined;
|
||||
this.scheduleWrite.cancel();
|
||||
};
|
||||
}
|
||||
|
||||
/** Newest first, including what other tabs and browsers recorded. Empty until recording has started. */
|
||||
async getEntries(): Promise<PageHistoryEntry[]> {
|
||||
if (!this.ready) {
|
||||
return [];
|
||||
}
|
||||
await this.ready;
|
||||
await this.sync(false);
|
||||
return [...this.state.entries];
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgets every recorded page, in every tab and browser, and persists right away. Resolves after the first
|
||||
* attempt whether or not it reached storage; a failed attempt is retried like any other change.
|
||||
*/
|
||||
async clear(): Promise<void> {
|
||||
if (!this.ready) {
|
||||
return;
|
||||
}
|
||||
await this.ready;
|
||||
this.state = clearHistory(this.state, Date.now());
|
||||
this.dirty = true;
|
||||
await this.writeNow();
|
||||
}
|
||||
|
||||
private async load(): Promise<void> {
|
||||
// An unreachable store must not seed: it may well hold a history already.
|
||||
if ((await this.sync(false)) === 'empty') {
|
||||
await this.seed();
|
||||
}
|
||||
const pending = this.pending;
|
||||
this.pending = undefined;
|
||||
pending?.forEach((change) => change());
|
||||
}
|
||||
|
||||
/**
|
||||
* First use for this user and org: carries the newest dashboards over from the recently-viewed impressions.
|
||||
* They have no visit time, so they sort after every recorded page and are the first to be evicted. A bridge
|
||||
* for users who had a Recent tab before page history; remove once that is a few releases back.
|
||||
*/
|
||||
private async seed(): Promise<void> {
|
||||
let uids: string[] = [];
|
||||
try {
|
||||
uids = await impressionSrv.getDashboardOpened();
|
||||
} catch (e) {
|
||||
console.warn('Page history: seed failed', e);
|
||||
}
|
||||
const seeded: PageHistoryEntry[] = uids
|
||||
.slice(0, PAGE_HISTORY_MAX_PER_KIND)
|
||||
.map((uid) => ({ kind: 'dashboard', uid, pathname: `/d/${uid}`, search: '' }));
|
||||
this.state = mergeStored(this.state, { clearedAt: 0, entries: seeded });
|
||||
this.persist();
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the stored copy into memory and, with `persist`, stores the result when it differs. `empty`: nothing
|
||||
* has ever been stored for this user and org. `unreachable`: a request failed and nothing was stored.
|
||||
*/
|
||||
private async sync(persist: boolean): Promise<'merged' | 'empty' | 'unreachable'> {
|
||||
let outcome: 'merged' | 'empty' = 'empty';
|
||||
try {
|
||||
await this.storage.updateItem(STORAGE_KEY, (raw) => {
|
||||
outcome = raw === null ? 'empty' : 'merged';
|
||||
// Runs again after a version conflict; `mergeStored` is idempotent, so that is safe.
|
||||
this.state = mergeStored(this.state, parseStored(raw));
|
||||
const next = serialize(this.state);
|
||||
return persist && next !== raw ? next : undefined;
|
||||
});
|
||||
return outcome;
|
||||
} catch (e) {
|
||||
console.warn('Page history: storage unavailable', e);
|
||||
return 'unreachable';
|
||||
}
|
||||
}
|
||||
|
||||
/** Hash deliberately ignored. */
|
||||
private apply(location: Location, isRewrite: boolean): void {
|
||||
const page = classifyPage(location.pathname, location.search);
|
||||
if (!page) {
|
||||
return;
|
||||
}
|
||||
// A page with nothing to resume gets no row, but a row it has is refreshed to where the user left it.
|
||||
const refreshOnly = isRewrite || hasNothingToResume(page, location.search, this.navTree());
|
||||
const search = recordableSearch(page, location.search);
|
||||
const at = Date.now();
|
||||
this.record(() => recordVisit(this.state, page, search, at, refreshOnly));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamps the chrome's title onto the row of the page the user is on, if that page has one. The chrome does not
|
||||
* say which page a nav belongs to and keeps the previous page's nav across a navigation within one route
|
||||
* (dashboard to dashboard, one app page to another), so a new row stays untitled until its own page sets its
|
||||
* nav. A nav the departed page sets after the navigation still lands on the new row; the page's own nav
|
||||
* replaces it once set.
|
||||
*/
|
||||
private setTitle(title: string | undefined): void {
|
||||
if (!title) {
|
||||
return;
|
||||
}
|
||||
const { pathname, search } = locationService.getLocation();
|
||||
const page = classifyPage(pathname, search);
|
||||
if (page) {
|
||||
const at = Date.now();
|
||||
this.record(() => recordTitle(this.state, page, title, at));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies `change` to the state, after the stored copy is in. Stamps are taken when the change is made, so a
|
||||
* replay keeps the order of events; the write it arms waits for the load as every write does.
|
||||
*/
|
||||
private record(change: () => HistoryState): void {
|
||||
if (this.pending) {
|
||||
this.pending.push(() => this.update(change()));
|
||||
this.persist();
|
||||
return;
|
||||
}
|
||||
this.update(change());
|
||||
}
|
||||
|
||||
/** Adopts a change made in this tab, if `next` is one: written at the end of the current window. */
|
||||
private update(next: HistoryState): void {
|
||||
if (next === this.state) {
|
||||
return;
|
||||
}
|
||||
this.state = next;
|
||||
this.persist();
|
||||
}
|
||||
|
||||
/** Something changed: written at the end of the current window. */
|
||||
private persist(): void {
|
||||
this.dirty = true;
|
||||
this.scheduleWrite();
|
||||
}
|
||||
|
||||
/** Writes now instead of at the end of the window. */
|
||||
private writeNow(): Promise<void> {
|
||||
this.scheduleWrite.cancel();
|
||||
return this.write();
|
||||
}
|
||||
|
||||
private async write(): Promise<void> {
|
||||
// Never overwrite the stored copy before it has been merged in.
|
||||
await this.ready;
|
||||
// Cleared first so a change made while this write is in flight stays pending.
|
||||
this.dirty = false;
|
||||
if ((await this.sync(true)) === 'unreachable') {
|
||||
this.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const pageHistorySrv = new PageHistorySrv();
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"scope": "actual shipped frontend from the verified Grafana13.3.1 image; public tag source is not substituted",
|
||||
"imageID": "sha256:1c88285f1dd391a62232c010e6c224846e6a73bdc583b3365be2eba614b7919e",
|
||||
"reportedCommit": "da3aa3ff574e7dbbf808c66b6daa744defed0441",
|
||||
"bundle": {"path":"/usr/share/grafana/public/build/18631.ceb2a2734f477243.js","bytes":3030265,"sha256":"b71e20545a118a186841598d30573cb34c7949ce89527e9b4ca8e451ef919458"},
|
||||
"map": {"path":"/usr/share/grafana/public/build/18631.ceb2a2734f477243.js.map","bytes":15209200,"sha256":"45ffad904b41b1d9901f400215b9efcac88e9a98baa0fb0fb9378407f8a56b8c"},
|
||||
"deliveredSources": [
|
||||
{"path":"packages/grafana-runtime/src/utils/userStorage.tsx","file":"history-user-storage-source.txt","sha256":"aee99a03048c1d7e639ad16e80d874508033a18f32c18955914dfc96624d1e28","reader":"fetchResource: status404 returns null; other failures throw; apiRequest sets showErrorAlert:false"},
|
||||
{"path":"public/app/core/services/pageHistory/pageHistorySrv.ts","file":"history-page-service-source.txt","sha256":"a8970b0388671b359a1721a6d6eb9913a5df4d30251fd40cb37621cfd0f5a2a2","reader":"start->load->sync(false); missing null means empty, then seed; ordinary writes throttled30000ms"}
|
||||
],
|
||||
"exactOwnedRoute":"/apis/userstorage.grafana.app/v0alpha1/namespaces/default/user-storage/grafana-page-history:bg4fowucaheyoa",
|
||||
"nativePositive":"history-normal-ui.json",
|
||||
"rawColdConsole404Count":2,
|
||||
"normalUIWriteHTTP":201,
|
||||
"sameKeyReloadGET":200,
|
||||
"unexpectedReloadErrors":0,
|
||||
"exception":"Only this proven expected missing-state GET404; no blanket404/403 whitelist and no claim that raw console errors were absent"
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import { get, noop } from 'lodash';
|
||||
import { useRef } from 'react';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
|
||||
import { usePluginContext, type UserStorage as UserStorageType, store } from '@grafana/data';
|
||||
|
||||
import { config } from '../config';
|
||||
import { type BackendSrvRequest, getBackendSrv } from '../services';
|
||||
|
||||
const baseURL = `/apis/userstorage.grafana.app/v0alpha1/namespaces/${config.namespace}/user-storage`;
|
||||
|
||||
// Per resourceName (e.g. "plugin-id:user-uid"): the spec, or `null` once a GET returned 404.
|
||||
// Only touched under the operation lock, so it never has to hold a pending load.
|
||||
const storageCache = new Map<string, UserStorageSpec | null>();
|
||||
|
||||
// Per resourceName: settles once the last queued operation has finished.
|
||||
const operationLocks = new Map<string, Promise<void>>();
|
||||
|
||||
// Each attempt costs one GET and one write; this bounds the cost of a key many tabs fight over.
|
||||
const WRITE_ATTEMPTS = 3;
|
||||
|
||||
/**
|
||||
* Clears the global storage cache. Used for testing purposes.
|
||||
* @internal
|
||||
*/
|
||||
export function _clearStorageCache() {
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
throw new Error('clearStorageCache() function can only be called from tests.');
|
||||
}
|
||||
storageCache.clear();
|
||||
operationLocks.clear();
|
||||
}
|
||||
|
||||
interface RequestOptions extends BackendSrvRequest {
|
||||
// rtk codegen sets this
|
||||
body?: BackendSrvRequest['data'];
|
||||
}
|
||||
|
||||
type UserStorageSpec = {
|
||||
data: { [key: string]: string };
|
||||
};
|
||||
|
||||
type UserStorageResource = {
|
||||
metadata: { resourceVersion: string };
|
||||
spec: UserStorageSpec;
|
||||
};
|
||||
|
||||
async function apiRequest<T>(requestOptions: RequestOptions) {
|
||||
try {
|
||||
const { data: responseData, ...meta } = await lastValueFrom(
|
||||
getBackendSrv().fetch<T>({
|
||||
...requestOptions,
|
||||
url: baseURL + requestOptions.url,
|
||||
data: requestOptions.body,
|
||||
showErrorAlert: false,
|
||||
})
|
||||
);
|
||||
return { data: responseData, meta };
|
||||
} catch (error) {
|
||||
return { error };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A class for interacting with the backend user storage.
|
||||
* Exposed internally only to avoid misuse (wrong service name).
|
||||
*
|
||||
* Two failure policies coexist on purpose. `getItem`, `setItem`, `deleteItem` and `allItems` fall back to
|
||||
* localStorage when a request fails, so a plugin keeps working. `updateItem` rejects instead: its callers
|
||||
* merge against the stored copy, and a merge over a copy the server never saw is worse than no write.
|
||||
*/
|
||||
export class UserStorage implements UserStorageType {
|
||||
private service: string;
|
||||
private resourceName: string;
|
||||
private userUID: string;
|
||||
private canUseUserStorage: boolean;
|
||||
|
||||
constructor(service: string) {
|
||||
this.service = service;
|
||||
this.userUID = config.bootData.user.uid === '' ? config.bootData.user.id.toString() : config.bootData.user.uid;
|
||||
this.resourceName = `${service}:${this.userUID}`;
|
||||
this.canUseUserStorage = config.bootData.user.isSignedIn;
|
||||
}
|
||||
|
||||
private localKey(key: string) {
|
||||
return `${this.resourceName}:${key}`;
|
||||
}
|
||||
|
||||
/** Runs `operation` once every earlier operation on this resourceName has settled, whether it succeeded or threw. */
|
||||
private runExclusive<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const previous = operationLocks.get(this.resourceName) ?? Promise.resolve();
|
||||
const result = previous.then(operation);
|
||||
const tail = result.then(noop, noop);
|
||||
operationLocks.set(this.resourceName, tail);
|
||||
tail.then(() => {
|
||||
if (operationLocks.get(this.resourceName) === tail) {
|
||||
operationLocks.delete(this.resourceName);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The stored resource, `null` when none exists yet (404). Throws on any other failure. */
|
||||
private async fetchResource(): Promise<UserStorageResource | null> {
|
||||
const response = await apiRequest<UserStorageResource>({ url: `/${this.resourceName}`, method: 'GET' });
|
||||
if ('error' in response) {
|
||||
if (get(response.error, 'status') === 404) {
|
||||
return null;
|
||||
}
|
||||
throw response.error;
|
||||
}
|
||||
return response.data;
|
||||
}
|
||||
|
||||
private createResource(data: UserStorageSpec['data']) {
|
||||
return apiRequest<UserStorageResource>({
|
||||
url: `/`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
metadata: { name: this.resourceName, labels: { user: this.userUID, service: this.service } },
|
||||
spec: { data },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Merge-patch; a `null` value deletes that key. With `metadata.resourceVersion` the server rejects a stale write. */
|
||||
private patchResource(body: {
|
||||
metadata?: { resourceVersion: string };
|
||||
spec: { data: Record<string, string | null> };
|
||||
}) {
|
||||
return apiRequest<UserStorageResource>({
|
||||
headers: { 'Content-Type': 'application/merge-patch+json' },
|
||||
url: `/${this.resourceName}`,
|
||||
method: 'PATCH',
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
/** Fills the cache on first use. Runs under the lock, so nothing reads the cache mid-load. Returns the load error, if any. */
|
||||
private async init(): Promise<unknown> {
|
||||
if (storageCache.has(this.resourceName)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
storageCache.set(this.resourceName, (await this.fetchResource())?.spec ?? null);
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
async getItem(key: string): Promise<string | null> {
|
||||
if (!this.canUseUserStorage) {
|
||||
return store.get(this.localKey(key)) ?? null;
|
||||
}
|
||||
return this.runExclusive(async () => {
|
||||
await this.init();
|
||||
const spec = storageCache.get(this.resourceName);
|
||||
if (!spec) {
|
||||
// No resource yet, or the load failed: fall back to localStorage
|
||||
return store.get(this.localKey(key)) ?? null;
|
||||
}
|
||||
return spec.data[key] ?? null;
|
||||
});
|
||||
}
|
||||
|
||||
async setItem(key: string, value: string): Promise<void> {
|
||||
if (!this.canUseUserStorage) {
|
||||
store.set(this.localKey(key), value);
|
||||
return;
|
||||
}
|
||||
return this.runExclusive(async () => {
|
||||
const error = await this.init();
|
||||
if (error) {
|
||||
store.set(this.localKey(key), value);
|
||||
return;
|
||||
}
|
||||
const spec = storageCache.get(this.resourceName);
|
||||
const result = spec
|
||||
? await this.patchResource({ spec: { data: { [key]: value } } })
|
||||
: await this.createResource({ [key]: value });
|
||||
if ('error' in result) {
|
||||
store.set(this.localKey(key), value);
|
||||
return;
|
||||
}
|
||||
storageCache.set(this.resourceName, { data: { ...spec?.data, [key]: value } });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-modify-write of one item against what is stored right now. `update` gets the stored value
|
||||
* (`null` when there is none) and returns the value to store, or `undefined` to store nothing.
|
||||
* Signed in: fetches the resource fresh, writes with its `metadata.resourceVersion` so the server
|
||||
* rejects a write over a copy it has not seen, and on that rejection re-reads and re-runs `update`
|
||||
* (`WRITE_ATTEMPTS` times). Every snapshot it fetches refreshes the cache, so a later `getItem` sees the
|
||||
* fresh value even when the write fails. Rejects when a request fails; nothing is written to localStorage.
|
||||
* Signed out: localStorage. There is no cross-tab lock, so two tabs updating at the same instant can drop
|
||||
* one update; the next update merges from storage again.
|
||||
*/
|
||||
async updateItem(key: string, update: (current: string | null) => string | undefined): Promise<void> {
|
||||
if (!this.canUseUserStorage) {
|
||||
const next = update(store.get(this.localKey(key)) ?? null);
|
||||
if (next !== undefined) {
|
||||
store.set(this.localKey(key), next);
|
||||
}
|
||||
return;
|
||||
}
|
||||
return this.runExclusive(async () => {
|
||||
for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt++) {
|
||||
const resource = await this.fetchResource();
|
||||
storageCache.set(this.resourceName, resource?.spec ?? null);
|
||||
const next = update(resource?.spec.data[key] ?? null);
|
||||
if (next === undefined) {
|
||||
return;
|
||||
}
|
||||
const result = resource
|
||||
? await this.patchResource({
|
||||
metadata: { resourceVersion: resource.metadata.resourceVersion },
|
||||
spec: { data: { [key]: next } },
|
||||
})
|
||||
: await this.createResource({ [key]: next });
|
||||
if ('error' in result) {
|
||||
// Stale version, or another client created the resource first: re-read and run `update` again.
|
||||
if (get(result.error, 'status') === 409) {
|
||||
continue;
|
||||
}
|
||||
throw result.error;
|
||||
}
|
||||
storageCache.set(this.resourceName, { data: { ...resource?.spec.data, [key]: next } });
|
||||
return;
|
||||
}
|
||||
throw new Error('User storage: conflicting writes');
|
||||
});
|
||||
}
|
||||
|
||||
async deleteItem(key: string): Promise<void> {
|
||||
if (!this.canUseUserStorage) {
|
||||
store.delete(this.localKey(key));
|
||||
return;
|
||||
}
|
||||
return this.runExclusive(async () => {
|
||||
const error = await this.init();
|
||||
const spec = storageCache.get(this.resourceName);
|
||||
if (error || !spec) {
|
||||
// Nothing to delete server-side (load failed or no resource); clear the localStorage fallback instead
|
||||
store.delete(this.localKey(key));
|
||||
return;
|
||||
}
|
||||
const result = await this.patchResource({ spec: { data: { [key]: null } } });
|
||||
if ('error' in result) {
|
||||
store.delete(this.localKey(key));
|
||||
return;
|
||||
}
|
||||
const { [key]: _, ...data } = spec.data;
|
||||
storageCache.set(this.resourceName, { data });
|
||||
});
|
||||
}
|
||||
|
||||
async allItems(): Promise<Record<string, string>> {
|
||||
if (!this.canUseUserStorage) {
|
||||
return store.all(`${this.resourceName}:`);
|
||||
}
|
||||
return this.runExclusive(async () => {
|
||||
await this.init();
|
||||
const spec = storageCache.get(this.resourceName);
|
||||
return spec ? { ...spec.data } : store.all(`${this.resourceName}:`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// This is a type alias to avoid breaking changes
|
||||
export interface PluginUserStorage extends UserStorageType {}
|
||||
|
||||
/**
|
||||
* A hook for interacting with the backend user storage (or local storage if not enabled).
|
||||
* @returns An scoped object for a plugin and a user with getItem and setItem functions.
|
||||
* @alpha Experimental
|
||||
*/
|
||||
export function usePluginUserStorage(): PluginUserStorage {
|
||||
const context = usePluginContext();
|
||||
const ref = useRef<[id: string, PluginUserStorage] | undefined>(undefined);
|
||||
|
||||
if (!context) {
|
||||
throw new Error(`No PluginContext found. The usePluginUserStorage() hook can only be used from a plugin.`);
|
||||
}
|
||||
|
||||
if (!ref.current || ref.current[0] !== context.meta.id) {
|
||||
ref.current = [context.meta.id, new UserStorage(context.meta.id)];
|
||||
}
|
||||
|
||||
return ref.current[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal Grafana-core only interface for constructing a UserStorage instance in a
|
||||
* react component.
|
||||
*/
|
||||
export function useUserStorage(service: string): UserStorageType {
|
||||
const ref = useRef<[service: string, UserStorageType] | undefined>(undefined);
|
||||
|
||||
if (!ref.current || ref.current[0] !== service) {
|
||||
ref.current = [service, new UserStorage(service)];
|
||||
}
|
||||
|
||||
return ref.current[1];
|
||||
}
|
||||
Reference in New Issue
Block a user