mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
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:
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user