feat(admin): show the allowance of place search, address search and routing in the TREK API card

GET /api/admin/service-identity lists places, photon and valhalla, each with
today's allowance read fresh from /v1/quota of its own host (cached for 20
seconds per host) and whether this instance asks it right now: Photon only
beside the public Nominatim, the TREK Valhalla only where the routing choice
comes to it. Photon and Valhalla are asked only with a key and only while
TREK_SERVICES_HOSTS lists them. The last allowance an answer stated is kept
per host for when a host does not answer.

The card lists the three services under each other in the look it had,
a service this instance does not ask dimmed and named as such.
This commit is contained in:
Maurice
2026-10-29 10:44:50 +01:00
committed by Maurice
parent 091ebed8e4
commit bc62eb0d6f
43 changed files with 531 additions and 89 deletions
@@ -42,7 +42,7 @@ export class IssuerError extends Error {
}
}
/** The four calls TREK makes to the key issuer at places.liketrek.com. */
/** The calls TREK makes to the key issuer at places.liketrek.com, and the allowance any liketrek host reports. */
@Injectable()
export class IssuerClient {
challenge(): Promise<IssuerAnswer<ServiceChallenge>> {
@@ -57,22 +57,25 @@ export class IssuerClient {
return this.call('POST', '/v1/register/renew', serviceKeyGrantSchema, { bearer: key });
}
/** Today's allowance of the key, or of the shared legacy pool without one. Costs no allowance itself. */
quota(key: string | null): Promise<IssuerAnswer<ServiceQuota>> {
return this.call('GET', '/v1/quota', serviceQuotaSchema, { bearer: key });
/**
* Today's allowance of the key at the host of `origin`, or of the shared
* legacy pool without one (only Places has that pool). Costs no allowance itself.
*/
quota(origin: string, key: string | null): Promise<IssuerAnswer<ServiceQuota>> {
return this.call('GET', '/v1/quota', serviceQuotaSchema, { bearer: key, origin });
}
private async call<T>(
method: 'GET' | 'POST',
path: string,
schema: z.ZodType<T>,
opts: { body?: RegistrationRequest; bearer?: string | null } = {},
opts: { body?: RegistrationRequest; bearer?: string | null; origin?: string } = {},
): Promise<IssuerAnswer<T>> {
const headers: Record<string, string> = { Accept: 'application/json', 'User-Agent': serviceUserAgent() };
if (opts.bearer) headers.Authorization = `Bearer ${opts.bearer}`;
if (opts.body) headers['Content-Type'] = 'application/json';
const res = await safeFetch(
`${SERVICE_ISSUER_ORIGIN}${path}`,
`${opts.origin ?? SERVICE_ISSUER_ORIGIN}${path}`,
{
method,
headers,
@@ -2,27 +2,37 @@ import type { QuotaReading } from './service-identity.helpers';
import { Injectable } from '@nestjs/common';
interface QuotaSighting extends QuotaReading {
/** When a liketrek service last answered this process. */
/** When this host last answered this process. */
seenAt: string;
}
/**
* The allowance as the last liketrek answer stated it. Kept in memory only:
* it is a fallback for the admin card when the issuer cannot be asked.
* The allowance as the last answer of each liketrek host stated it. Kept in
* memory only: it is a fallback for the admin card when a host cannot be asked.
*/
@Injectable()
export class QuotaTracker {
private last: QuotaSighting | null = null;
private readonly byHost = new Map<string, QuotaSighting>();
record(reading: QuotaReading | null, at = new Date()): void {
this.last = {
tier: reading?.tier ?? this.last?.tier ?? null,
quota: reading?.quota ?? this.last?.quota ?? null,
record(host: string, reading: QuotaReading | null, at = new Date()): void {
const last = this.byHost.get(host);
this.byHost.set(host, {
tier: reading?.tier ?? last?.tier ?? null,
quota: reading?.quota ?? last?.quota ?? null,
seenAt: at.toISOString(),
};
});
}
latest(): QuotaSighting | null {
return this.last;
latest(host: string): QuotaSighting | null {
return this.byHost.get(host) ?? null;
}
/** The most recent answer of any host. */
newest(): QuotaSighting | null {
let newest: QuotaSighting | null = null;
for (const sighting of this.byHost.values()) {
if (!newest || sighting.seenAt > newest.seenAt) newest = sighting;
}
return newest;
}
}
@@ -1,2 +1,8 @@
/** The issuer of installation keys: the Places host itself, so no new egress domain is needed. */
export const SERVICE_ISSUER_ORIGIN = 'https://places.liketrek.com';
/** The TREK services' Photon, the address search that stands in for the public Nominatim. */
export const PHOTON_ORIGIN = 'https://photon.liketrek.com';
/** The Nominatim TREK asks when NOMINATIM_URL names none of the admin's own. */
export const PUBLIC_NOMINATIM_URL = 'https://nominatim.openstreetmap.org';
@@ -1,30 +1,42 @@
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { servicesConfig } from '../app-config/tokens';
import { logDebug } from '../audit/audit-log.logger';
import { SettingsService } from '../settings/settings.service';
import { IssuerClient } from './issuer.client';
import { QuotaTracker } from './quota-tracker';
import { ServiceClock } from './service-clock';
import { SERVICE_ISSUER_ORIGIN } from './service-identity.constants';
import { isAllowlisted } from './service-identity.helpers';
import { PHOTON_ORIGIN, PUBLIC_NOMINATIM_URL, SERVICE_ISSUER_ORIGIN } from './service-identity.constants';
import { isAllowlisted, sameServiceUrl } from './service-identity.helpers';
import { ServiceKeyService, type KeySnapshot } from './service-key.service';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import {
SERVICE_NAMES,
resolveValhallaProvider,
serviceTierSchema,
type ServiceAllowance,
type ServiceIdentityStatus,
type ServiceName,
type ServiceQuota,
type ServiceQuotaView,
type ServiceTier,
} from '@trek/shared';
/** The admin card refreshes every 30 s; one issuer call serves every open card for this long. */
/** The admin card refreshes every 30 s; one call per host serves every open card for this long. */
const QUOTA_CACHE_MS = 20_000;
const OFF: ServiceIdentityStatus = { state: 'off', tier: null, keySource: null, quota: null, lastSeenAt: null };
const OFF: ServiceIdentityStatus = { state: 'off', tier: null, keySource: null, services: [], lastSeenAt: null };
interface CachedQuota {
bearer: string | null;
at: number;
quota: ServiceQuota | null;
}
/** What the admin sees of this installation's identity, and the one thing an admin can do with it. */
@Injectable()
export class ServiceIdentityService {
private cached: { bearer: string | null; at: number; quota: ServiceQuota | null } | null = null;
private readonly cached = new Map<string, CachedQuota>();
constructor(
@Inject(servicesConfig.KEY) private readonly config: ConfigType<typeof servicesConfig>,
@@ -32,59 +44,109 @@ export class ServiceIdentityService {
private readonly issuer: IssuerClient,
private readonly tracker: QuotaTracker,
private readonly clock: ServiceClock,
private readonly settings: SettingsService,
private readonly env: RuntimeEnvService,
) {}
async status(): Promise<ServiceIdentityStatus> {
const key = await this.keys.snapshot();
if (key.state === 'off') return OFF;
const fresh = await this.freshQuota(key.bearer);
const seen = this.tracker.latest();
const inUse = await this.servicesInUse(key);
const fresh = await Promise.all(SERVICE_NAMES.map((service) => this.freshQuota(service, key.bearer)));
const services = SERVICE_NAMES.map((service, index): ServiceAllowance => ({
service,
inUse: inUse[service],
quota: viewOf(fresh[index]) ?? this.tracker.latest(hostOf(this.originOf(service)))?.quota ?? null,
}));
return {
state: key.state,
tier: fresh?.tier ?? seen?.tier ?? keyTier(key),
tier:
fresh[SERVICE_NAMES.indexOf('places')]?.tier ??
this.tracker.latest(hostOf(SERVICE_ISSUER_ORIGIN))?.tier ??
keyTier(key),
keySource: key.source,
quota: fresh ? quotaView(fresh) : (seen?.quota ?? null),
lastSeenAt: seen?.seenAt ?? null,
services,
lastSeenAt: this.tracker.newest()?.seenAt ?? null,
};
}
async regenerate(): Promise<ServiceIdentityStatus> {
await this.keys.regenerate();
this.cached = null;
this.cached.clear();
return this.status();
}
/** GET /v1/quota, which costs no allowance; null when the issuer cannot or may not be asked right now. */
private async freshQuota(bearer: string | null): Promise<ServiceQuota | null> {
if (bearer && !this.issuerMaySeeKey()) return null;
if (this.cached && this.cached.bearer === bearer && Date.now() - this.cached.at < QUOTA_CACHE_MS) {
return this.cached.quota;
}
private originOf(service: ServiceName): string {
if (service === 'photon') return PHOTON_ORIGIN;
return service === 'valhalla' ? this.config.valhallaUrl : SERVICE_ISSUER_ORIGIN;
}
/**
* Whether this instance asks each service right now. Places is in use
* whenever the identity is; the other two need the key itself, since they
* have no shared pool. Photon stands in for the public Nominatim only, and
* the TREK Valhalla answers only where the routing choice comes to it.
*/
private async servicesInUse(key: KeySnapshot): Promise<Record<ServiceName, boolean>> {
const keyed = (service: ServiceName) => key.bearer !== null && this.mayCarryKey(this.originOf(service));
const defaults = await this.settings.getAdminUserDefaults();
const routing = resolveValhallaProvider({
provider: defaults.routing_valhalla_provider,
valhallaUrl: defaults.valhalla_base_url,
routingUrl: defaults.routing_base_url,
trekAvailable: keyed('valhalla'),
});
return {
places: true,
photon: keyed('photon') && sameServiceUrl(this.env.env().integrations.nominatimUrl, PUBLIC_NOMINATIM_URL),
valhalla: routing === 'trek',
};
}
/**
* GET /v1/quota of the service's host, which costs no allowance; null when
* the host cannot or may not be asked right now. Without a key only Places
* answers, for the shared pool.
*/
private async freshQuota(service: ServiceName, bearer: string | null): Promise<ServiceQuota | null> {
const origin = this.originOf(service);
if (bearer ? !this.mayCarryKey(origin) : service !== 'places') return null;
const cached = this.cached.get(origin);
if (cached && cached.bearer === bearer && Date.now() - cached.at < QUOTA_CACHE_MS) return cached.quota;
let quota: ServiceQuota | null = null;
try {
const answer = await this.issuer.quota(bearer);
const answer = await this.issuer.quota(origin, bearer);
this.clock.learn(answer.serverMs);
quota = answer.body;
} catch (err) {
logDebug(`TREK services: quota not available: ${err instanceof Error ? err.message : String(err)}`);
logDebug(`TREK services: ${service} quota not available: ${err instanceof Error ? err.message : String(err)}`);
}
this.cached = { bearer, at: Date.now(), quota };
this.cached.set(origin, { bearer, at: Date.now(), quota });
return quota;
}
/** Even the issuer sees the key only while TREK_SERVICES_HOSTS lists it. */
private issuerMaySeeKey(): boolean {
return isAllowlisted(new URL(SERVICE_ISSUER_ORIGIN), this.config.hosts);
/** A host sees the key only while TREK_SERVICES_HOSTS lists it. */
private mayCarryKey(origin: string): boolean {
try {
return isAllowlisted(new URL(origin), this.config.hosts);
} catch {
return false;
}
}
}
function hostOf(origin: string): string {
return new URL(origin).hostname.toLowerCase();
}
function keyTier(key: KeySnapshot): ServiceTier | null {
if (!key.key) return key.state === 'legacy' || key.state === 'registering' ? 'legacy' : null;
const tier = serviceTierSchema.safeParse(key.key.payload.q);
return tier.success ? tier.data : null;
}
function quotaView(quota: ServiceQuota): ServiceQuotaView {
function viewOf(quota: ServiceQuota | null): ServiceQuotaView | null {
if (!quota) return null;
return {
limit: quota.limit,
used: quota.used,
@@ -38,7 +38,7 @@ export class ServiceRequestIdentity extends ServiceIdentityPort {
observe(url: URL, response: Response): void {
if (!isAllowlisted(url, this.config.hosts)) return;
this.clock.learn(serverDateMs(response.headers));
this.tracker.record(readQuotaHeaders(response.headers));
this.tracker.record(url.hostname.toLowerCase(), readQuotaHeaders(response.headers));
if (response.ok) this.keys.noteAccepted();
else if (response.status === 401) this.keys.noteInvalid();
else if (response.status === 403) void this.checkRevocation(response.clone());
+57 -7
View File
@@ -38,18 +38,25 @@ const ADMIN = 2;
const ENV_KEY = serviceKeyTokenFor({ i: 'from-environment', iat: 1_793_000_000, exp: 4_102_444_800, q: 'own' });
const STORED_KEY = serviceKeyTokenFor({ i: 'registered-one', iat: 1_793_000_000, exp: 4_102_444_800 });
const QUOTA = { tier: 'own', limit: 50_000, used: 1_234, remaining: 48_766, reset_at: 1_793_059_200, per_minute: 600 };
const VIEW = { limit: 50_000, used: 1_234, remaining: 48_766, resetAt: new Date(1_793_059_200_000).toISOString() };
const writeAudit = vi.fn();
let orm: TestOrm;
type ServicesConfig = { mode: 'auto' | 'off'; key: string | null; hosts: string[] };
type ServicesConfig = { mode: 'auto' | 'off'; key: string | null; hosts: string[]; valhallaUrl: string };
async function build(config: Partial<ServicesConfig> = {}) {
const moduleRef = await Test.createTestingModule({
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), ServiceIdentityModule],
})
.overrideProvider(servicesConfig.KEY)
.useValue({ mode: 'auto', key: null, hosts: ['places.liketrek.com'], ...config })
.useValue({
mode: 'auto',
key: null,
hosts: ['places.liketrek.com'],
valhallaUrl: 'https://valhalla.liketrek.com',
...config,
})
.overrideProvider(AuditService)
.useValue({ writeAudit })
.compile();
@@ -61,7 +68,7 @@ async function build(config: Partial<ServicesConfig> = {}) {
return nest;
}
/** The issuer as places.liketrek.com answers /v1/quota. */
/** Every liketrek host as it answers /v1/quota. */
function issuerAnswers(status = 200) {
safeFetch.mockImplementation(async () =>
status === 200
@@ -107,16 +114,21 @@ describe('with a key from TREK_SERVICES_KEY', () => {
expect((await request(server).post('/api/admin/service-identity/regenerate').set(as(USER))).status).toBe(403);
});
it('SIE2E-002: shows the allowance the issuer reports for that key', async () => {
it('SIE2E-002: shows the allowance the issuer reports for that key, and no other host sees it', async () => {
const res = await request(app.getHttpServer()).get('/api/admin/service-identity').set(as(ADMIN));
expect(res.status).toBe(200);
expect(res.body).toEqual({
state: 'connected',
tier: 'own',
keySource: 'env',
quota: { limit: 50_000, used: 1_234, remaining: 48_766, resetAt: new Date(1_793_059_200_000).toISOString() },
services: [
{ service: 'places', inUse: true, quota: VIEW },
{ service: 'photon', inUse: false, quota: null },
{ service: 'valhalla', inUse: false, quota: null },
],
lastSeenAt: null,
});
expect(safeFetch).toHaveBeenCalledTimes(1);
const [url, init] = safeFetch.mock.calls[0] as [string, RequestInit & { headers: Record<string, string> }];
expect(url).toBe('https://places.liketrek.com/v1/quota');
expect(init.headers.Authorization).toBe(`Bearer ${ENV_KEY}`);
@@ -147,7 +159,8 @@ describe('with a key the installation registered', () => {
issuerAnswers(503);
const res = await request(app.getHttpServer()).get('/api/admin/service-identity').set(as(ADMIN));
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ state: 'connected', tier: 'std', keySource: 'registered', quota: null });
expect(res.body).toMatchObject({ state: 'connected', tier: 'std', keySource: 'registered' });
expect(res.body.services[0]).toEqual({ service: 'places', inUse: true, quota: null });
});
it('SIE2E-011: a new identity drops the stored key, is audited, and leaves the shared pool until the next search', async () => {
@@ -166,12 +179,49 @@ describe('with a key the installation registered', () => {
});
});
describe('with every liketrek host listed in TREK_SERVICES_HOSTS', () => {
const ALL_HOSTS = ['places.liketrek.com', 'photon.liketrek.com', 'valhalla.liketrek.com'];
it('SIE2E-030: asks each host for its own allowance and says which services this instance uses', async () => {
const app = await build({ key: ENV_KEY, hosts: ALL_HOSTS });
try {
const res = await request(app.getHttpServer()).get('/api/admin/service-identity').set(as(ADMIN));
expect(res.status).toBe(200);
expect(res.body.services).toEqual([
{ service: 'places', inUse: true, quota: VIEW },
{ service: 'photon', inUse: true, quota: VIEW },
{ service: 'valhalla', inUse: true, quota: VIEW },
]);
const asked = safeFetch.mock.calls.map(([url]) => String(url)).sort();
expect(asked).toEqual([
'https://photon.liketrek.com/v1/quota',
'https://places.liketrek.com/v1/quota',
'https://valhalla.liketrek.com/v1/quota',
]);
} finally {
await app.close();
}
});
it('SIE2E-031: the routing service is not in use once the admin picks FOSSGIS', async () => {
const app = await build({ key: ENV_KEY, hosts: ALL_HOSTS });
await upsertRow(orm, AppSettings, { key: 'default_user_setting_routing_valhalla_provider', value: '"fossgis"' });
try {
const res = await request(app.getHttpServer()).get('/api/admin/service-identity').set(as(ADMIN));
expect(res.body.services[2]).toEqual({ service: 'valhalla', inUse: false, quota: VIEW });
} finally {
await deleteRows(orm, AppSettings, { key: 'default_user_setting_routing_valhalla_provider' });
await app.close();
}
});
});
describe('with TREK_SERVICES=off', () => {
it('SIE2E-020: says so and asks the issuer nothing', async () => {
const app = await build({ mode: 'off' });
try {
const res = await request(app.getHttpServer()).get('/api/admin/service-identity').set(as(ADMIN));
expect(res.body).toEqual({ state: 'off', tier: null, keySource: null, quota: null, lastSeenAt: null });
expect(res.body).toEqual({ state: 'off', tier: null, keySource: null, services: [], lastSeenAt: null });
expect(safeFetch).not.toHaveBeenCalled();
const regenerate = await request(app.getHttpServer())
.post('/api/admin/service-identity/regenerate')
@@ -59,10 +59,19 @@ describe('IssuerClient', () => {
const quota = { tier: 'legacy', limit: 3000, used: 3, remaining: 2997, reset_at: 1_793_059_200, per_minute: 60 };
safeFetch.mockResolvedValueOnce(json(quota));
expect((await issuer.quota(null)).body).toEqual(quota);
expect((await issuer.quota('https://places.liketrek.com', null)).body).toEqual(quota);
expect(lastCall().url).toBe('https://places.liketrek.com/v1/quota');
expect(lastCall().init.headers).not.toHaveProperty('Authorization');
});
it('SIISS-006: reads the allowance of another liketrek host at its own /v1/quota', async () => {
const quota = { tier: 'std', limit: 20_000, used: 5, remaining: 19_995, reset_at: 1_793_059_200, per_minute: 120 };
safeFetch.mockResolvedValueOnce(json(quota));
expect((await issuer.quota('https://valhalla.liketrek.com', 'tk1.a.b.c')).body).toEqual(quota);
expect(lastCall().url).toBe('https://valhalla.liketrek.com/v1/quota');
expect(lastCall().init.headers.Authorization).toBe('Bearer tk1.a.b.c');
});
it('SIISS-004: turns a refusal into an IssuerError with the wait it asked for', async () => {
safeFetch.mockResolvedValueOnce(json({ error: 'slow_down' }, 429, { 'Retry-After': '90' }));
const err = await issuer.challenge().catch((e: unknown) => e);
@@ -1,8 +1,10 @@
/**
* ServiceIdentityService: what the admin card reads. A fresh allowance from
* the issuer when it answers, the last one a liketrek answer stated when it
* does not, nothing at all while the services are off.
* each liketrek host when it answers, the last one that host stated when it
* does not, nothing at all while the services are off; and which of the
* three services this instance asks.
*/
import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
import { servicesConfig } from '../../../../src/nest/app-config/tokens';
import { IssuerClient } from '../../../../src/nest/service-identity/issuer.client';
import { QuotaTracker } from '../../../../src/nest/service-identity/quota-tracker';
@@ -10,6 +12,7 @@ import { ServiceClock } from '../../../../src/nest/service-identity/service-cloc
import { ServiceIdentityService } from '../../../../src/nest/service-identity/service-identity.service';
import { parseServiceKey } from '../../../../src/nest/service-identity/service-key.format';
import { ServiceKeyService, type KeySnapshot } from '../../../../src/nest/service-identity/service-key.service';
import { SettingsService } from '../../../../src/nest/settings/settings.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { serviceKeyTokenFor } from '../../../helpers/service-keys';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
@@ -22,7 +25,17 @@ const QUOTA = { tier: 'std', limit: 10_000, used: 250, remaining: 9_750, reset_a
const keys = { snapshot: vi.fn(async (): Promise<KeySnapshot> => CONNECTED), regenerate: vi.fn(async () => undefined) };
const issuer = { quota: vi.fn() };
const config = { mode: 'auto' as const, key: null, hosts: ['places.liketrek.com'] };
const config = {
mode: 'auto' as const,
key: null,
hosts: ['places.liketrek.com'],
valhallaUrl: 'https://valhalla.liketrek.com',
};
const ALL_HOSTS = ['places.liketrek.com', 'photon.liketrek.com', 'valhalla.liketrek.com'];
const defaults = vi.fn(async (): Promise<Record<string, unknown>> => ({}));
const nominatim = { url: 'https://nominatim.openstreetmap.org' };
const env = { env: () => ({ integrations: { nominatimUrl: nominatim.url } }) };
const VIEW = { limit: 10_000, used: 250, remaining: 9_750, resetAt: new Date(1_793_059_200_000).toISOString() };
const testDb = createSnapshotTestDb();
let t: TestModule;
@@ -31,6 +44,8 @@ let identity: ServiceIdentityService;
beforeEach(async () => {
vi.clearAllMocks();
config.hosts = ['places.liketrek.com'];
nominatim.url = 'https://nominatim.openstreetmap.org';
defaults.mockResolvedValue({});
issuer.quota.mockResolvedValue({ body: QUOTA, serverMs: null });
t = await createTestModule({
db: testDb,
@@ -42,6 +57,8 @@ beforeEach(async () => {
{ provide: ServiceKeyService, useValue: keys },
{ provide: IssuerClient, useValue: issuer },
{ provide: servicesConfig.KEY, useValue: config },
{ provide: SettingsService, useValue: { getAdminUserDefaults: defaults } },
{ provide: RuntimeEnvService, useValue: env },
],
});
identity = t.get(ServiceIdentityService);
@@ -60,10 +77,15 @@ describe('ServiceIdentityService.status', () => {
state: 'connected',
tier: 'std',
keySource: 'registered',
quota: { limit: 10_000, used: 250, remaining: 9_750, resetAt: new Date(1_793_059_200_000).toISOString() },
services: [
{ service: 'places', inUse: true, quota: VIEW },
{ service: 'photon', inUse: false, quota: null },
{ service: 'valhalla', inUse: false, quota: null },
],
lastSeenAt: null,
});
expect(issuer.quota).toHaveBeenCalledWith(TOKEN);
expect(issuer.quota).toHaveBeenCalledTimes(1);
expect(issuer.quota).toHaveBeenCalledWith('https://places.liketrek.com', TOKEN);
});
it('SISVC-002: asks the issuer once per 20 seconds, however often the card refreshes', async () => {
@@ -78,24 +100,31 @@ describe('ServiceIdentityService.status', () => {
it('SISVC-003: falls back to the last stated allowance, then to the class in the key', async () => {
issuer.quota.mockRejectedValue(new Error('fetch failed'));
expect(await identity.status()).toMatchObject({ tier: 'hosted', quota: null });
t.get(QuotaTracker).record({ tier: 'std', quota: { limit: 5, used: 1, remaining: 4, resetAt: 'x' } });
const unanswered = await identity.status();
expect(unanswered.tier).toBe('hosted');
expect(unanswered.services[0]).toEqual({ service: 'places', inUse: true, quota: null });
t.get(QuotaTracker).record('places.liketrek.com', {
tier: 'std',
quota: { limit: 5, used: 1, remaining: 4, resetAt: 'x' },
});
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() + 21_000);
expect(await identity.status()).toMatchObject({ tier: 'std', quota: { limit: 5 }, lastSeenAt: expect.any(String) });
const remembered = await identity.status();
expect(remembered).toMatchObject({ tier: 'std', lastSeenAt: expect.any(String) });
expect(remembered.services[0].quota).toMatchObject({ limit: 5 });
});
it('SISVC-004: asks for the shared pool without a key, and asks nothing while off', async () => {
keys.snapshot.mockResolvedValueOnce({ state: 'legacy', key: null, source: null, bearer: null });
await identity.status();
expect(issuer.quota).toHaveBeenCalledWith(null);
expect(issuer.quota).toHaveBeenCalledWith('https://places.liketrek.com', null);
keys.snapshot.mockResolvedValueOnce({ state: 'off', key: null, source: null, bearer: null });
expect(await identity.status()).toEqual({
state: 'off',
tier: null,
keySource: null,
quota: null,
services: [],
lastSeenAt: null,
});
expect(issuer.quota).toHaveBeenCalledTimes(1);
@@ -107,12 +136,60 @@ describe('ServiceIdentityService.status', () => {
const after = await identity.regenerate();
expect(keys.regenerate).toHaveBeenCalledTimes(1);
expect(after.state).toBe('registering');
expect(issuer.quota).toHaveBeenLastCalledWith(null);
expect(issuer.quota).toHaveBeenLastCalledWith('https://places.liketrek.com', null);
});
it('SISVC-006: never shows the key to the issuer when TREK_SERVICES_HOSTS leaves it out', async () => {
config.hosts = ['gate.example.org'];
expect(await identity.status()).toMatchObject({ state: 'connected', tier: 'hosted', quota: null });
const status = await identity.status();
expect(status).toMatchObject({ state: 'connected', tier: 'hosted' });
expect(status.services.map(({ quota }) => quota)).toEqual([null, null, null]);
expect(issuer.quota).not.toHaveBeenCalled();
});
it('SISVC-007: asks each listed host for its own allowance, once per 20 seconds each', async () => {
config.hosts = ALL_HOSTS;
const status = await identity.status();
expect(status.services).toEqual([
{ service: 'places', inUse: true, quota: VIEW },
{ service: 'photon', inUse: true, quota: VIEW },
{ service: 'valhalla', inUse: true, quota: VIEW },
]);
expect(issuer.quota.mock.calls.map(([origin]) => origin)).toEqual([
'https://places.liketrek.com',
'https://photon.liketrek.com',
'https://valhalla.liketrek.com',
]);
await identity.status();
expect(issuer.quota).toHaveBeenCalledTimes(3);
});
it('SISVC-008: asks Photon and Valhalla nothing without a key, since only Places has a shared pool', async () => {
config.hosts = ALL_HOSTS;
keys.snapshot.mockResolvedValueOnce({ state: 'legacy', key: null, source: null, bearer: null });
const status = await identity.status();
expect(status.services.map(({ inUse }) => inUse)).toEqual([true, false, false]);
expect(issuer.quota).toHaveBeenCalledTimes(1);
});
it('SISVC-009: Photon is not in use beside an own Nominatim, the TREK Valhalla not beside another routing choice', async () => {
config.hosts = ALL_HOSTS;
nominatim.url = 'https://geocode.example.org';
defaults.mockResolvedValue({ valhalla_base_url: 'https://valhalla.example.org' });
const status = await identity.status();
expect(status.services.map(({ inUse }) => inUse)).toEqual([true, false, false]);
defaults.mockResolvedValue({ routing_base_url: 'https://osrm.example.org', routing_valhalla_provider: 'trek' });
expect((await identity.status()).services[2].inUse).toBe(true);
});
it('SISVC-010: shows the last allowance a host stated while it does not answer, each host its own', async () => {
config.hosts = ALL_HOSTS;
issuer.quota.mockRejectedValue(new Error('fetch failed'));
const view = { limit: 7, used: 2, remaining: 5, resetAt: 'x' };
t.get(QuotaTracker).record('valhalla.liketrek.com', { tier: 'std', quota: view });
const status = await identity.status();
expect(status.services.map(({ quota }) => quota)).toEqual([null, null, view]);
expect(status.tier).toBe('hosted');
});
});
@@ -90,7 +90,11 @@ describe('observe', () => {
'X-TREK-Quota-Reset': '1793059200',
}),
);
expect(t.get(QuotaTracker).latest()).toMatchObject({ tier: 'std', quota: { limit: 10_000, used: 1_000 } });
expect(t.get(QuotaTracker).latest('places.liketrek.com')).toMatchObject({
tier: 'std',
quota: { limit: 10_000, used: 1_000 },
});
expect(t.get(QuotaTracker).latest('valhalla.liketrek.com')).toBeNull();
expect(t.get(ServiceClock).nowSeconds()).toBeGreaterThan(Math.floor(Date.now() / 1000) + 100);
expect(keys.noteAccepted).toHaveBeenCalledTimes(1);
});
@@ -107,10 +111,11 @@ describe('observe', () => {
});
it('SIREQ-013: learns nothing from a host that is not allowlisted', () => {
const before = t.get(QuotaTracker).latest();
const before = t.get(QuotaTracker).newest();
identity.observe(new URL('https://mirror.example.org/v1/search'), answer(401, '{}', { 'X-TREK-Tier': 'own' }));
expect(keys.noteInvalid).not.toHaveBeenCalled();
expect(t.get(QuotaTracker).latest()).toBe(before);
expect(t.get(QuotaTracker).newest()).toBe(before);
expect(t.get(QuotaTracker).latest('mirror.example.org')).toBeNull();
});
});