Commit 0be738e7 authored by Guillaume Perréal's avatar Guillaume Perréal
Browse files

Split le cache.

parent f2718fac
import { HttpHeaderResponse } from '@angular/common/http';
import { inject, TestBed } from '@angular/core/testing';
import * as _ from 'lodash';
import { forkJoin, Observable } from 'rxjs';
import { Observable } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { MarbleTestScheduler } from '../../../testing/marbles';
import { Collection, IRI, IRI_PROPERTY, Resource } from '../../shared/models';
import { safeForkJoin } from '../../shared/rxjs';
import { ResourceCache } from './cache.service';
import { IRIMismatchError, MissingIRIError, ResourceCache, ValueHolder } from './cache.service';
import { Collection, IRI, Resource } from '../types';
describe('cache.service', () => {
interface MyResource extends Resource {
interface MyResource extends Resource {
readonly '@id': IRI<MyResource>;
readonly '@type': 'MyResource';
value: string;
value2?: string;
}
}
function iri(x: string): IRI<MyResource> {
function iri(x: string): IRI<MyResource> {
return x as any;
}
}
const MY_IRI = iri('/bla/a');
const OTHER_IRI = iri('/bla/B');
const VALUES: { [name: string]: MyResource } = {
const MY_IRI = iri('/bla/a');
const OTHER_IRI = iri('/bla/B');
const VALUES: { [name: string]: MyResource } = {
a: { '@id': MY_IRI, '@type': 'MyResource', value: 'foo' },
b: { '@id': MY_IRI, '@type': 'MyResource', value: 'bar' },
c: { '@id': MY_IRI, '@type': 'MyResource', value: 'bar', value2: 'quz' },
c: {
'@id': MY_IRI,
'@type': 'MyResource',
value: 'bar',
value2: 'quz',
},
d: { '@id': OTHER_IRI, '@type': 'MyResource', value: 'zig' },
};
let scheduler: MarbleTestScheduler<any>;
beforeEach(() => {
};
let scheduler: MarbleTestScheduler<any>;
beforeEach(() => {
scheduler = MarbleTestScheduler.create(VALUES, 'error');
});
describe('ValueHolder', () => {
let holder: ValueHolder<any>;
beforeEach(() => {
holder = new ValueHolder<MyResource>(iri('/bla/a'));
});
it('should be created', () => {
expect(holder).toBeTruthy();
});
describe('.set()', () => {
function testSet({ value, error, SET_M }: any) {
scheduler.withError(error).run(({ expectObservable }) => {
expectObservable(holder.set(value)).toBe(SET_M);
});
}
it('should provide the value', () =>
testSet({
value: VALUES.a,
SET_M: '(a|)',
}));
it(`should refuse value without ${IRI_PROPERTY}`, () =>
testSet({
value: {},
error: new MissingIRIError(),
SET_M: '#',
}));
it('should refuse value with different @id', () =>
testSet({
value: { '@id': iri('bar') },
error: new IRIMismatchError(MY_IRI, iri('bar')),
SET_M: '#',
}));
it('should always points to the same instance', () => {
forkJoin(holder.set(VALUES.a), holder.set(VALUES.b)).subscribe(([a, b]: MyResource[]) => {
expect(a).toBe(b);
});
});
});
describe('.update()', () => {
it('should provide the value from the server', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ_M = '---a|';
const UPD_M = '--(a|) ';
const request$ = cold(REQ_M);
expectObservable(holder.update(request$)).toBe(UPD_M);
}));
it('should cancel pending requests', () => {
const LOCAL_VALUES = {
a: VALUES.a,
b: VALUES.b,
j: [VALUES.b, VALUES.b],
};
const REQ1_M = '---a|';
const REQ2_M = 'b| ';
const UPDA_M = '(j|) ';
const REQ1_S = '(^!) ';
const REQ2_S = '(^!) ';
scheduler.withValues(LOCAL_VALUES).run(({ cold, expectObservable, expectSubscriptions }) => {
const request1$ = cold(REQ1_M);
const request2$ = cold(REQ2_M);
expectObservable(
safeForkJoin([
//
holder.update(request1$),
holder.update(request2$),
]),
).toBe(UPDA_M);
expectSubscriptions(request1$.subscriptions).toBe(REQ1_S);
expectSubscriptions(request2$.subscriptions).toBe(REQ2_S);
});
});
it('should propagate errors', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ_M = '#';
const UPD_M = '#';
const request$ = cold(REQ_M);
expectObservable(holder.update(request$)).toBe(UPD_M);
}));
it('should restart on errors', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ1_M = '#';
const UPD1_M = '#';
const obs$ = holder.update(cold(REQ1_M));
expectObservable(obs$).toBe(UPD1_M);
const REQ2_M = '-a|';
const UPD2_M = '-a|';
const obs2$ = holder.update(cold(REQ2_M));
expectObservable(obs2$).toBe(UPD2_M);
}));
});
describe('.listen()', () => {
function testListen({ REQUEST_M, LISTEN_M, initial }: any) {
scheduler.run(({ cold, expectObservable }) => {
if (initial) {
holder.set(initial);
}
expectObservable(holder.listen(() => cold(REQUEST_M))).toBe(LISTEN_M);
});
}
it('should provide the value', () =>
testListen({
initial: VALUES.a,
REQUEST_M: /**/ ' ',
LISTEN_M: /***/ '(a|)',
}));
it('should cache the value', () =>
testListen({
initial: VALUES.a,
REQUEST_M: /**/ 'b| ',
LISTEN_M: /***/ '(a|)',
}));
it('should propagate errors', () =>
testListen({
REQUEST_M: /**/ '#',
LISTEN_M: /***/ '#',
}));
});
it('.invalidate() should cause the value to be requested again', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQUEST_M = /**/ '(a|)';
const LISTEN_M = /***/ '(a|)';
const requestFactory = jasmine.createSpy('requestFactory');
requestFactory.and.returnValue(cold(REQUEST_M));
return holder
.set(VALUES.a)
.toPromise()
.then(() => holder.invalidate())
.then(() => expectObservable(holder.listen(requestFactory)).toBe(LISTEN_M))
.then(() => expect(requestFactory).toHaveBeenCalled());
}));
});
});
describe('ResourceCache', () => {
describe('ResourceCache', () => {
beforeEach(() =>
TestBed.configureTestingModule({
providers: [ResourceCache],
......@@ -216,11 +62,12 @@ describe('cache.service', () => {
const getQuery$ = cold('a|');
const getQuery2$ = cold('b|');
// tslint:disable-next-line:rxjs-finnish
const queries$ = cold('ab|', { a: getQuery$, b: getQuery2$ });
const queries$ = cold('ab|', {
a: getQuery$,
b: getQuery2$,
});
expectObservable(queries$.pipe(mergeMap((query$) => service.get(MY_IRI, () => query$)))).toBe(
'aa|',
);
expectObservable(queries$.pipe(mergeMap((query$) => service.get(MY_IRI, () => query$)))).toBe('aa|');
}),
));
......@@ -245,7 +92,10 @@ describe('cache.service', () => {
const putRequest$ = cold('a|');
const putRequest2$ = cold('b|');
// tslint:disable-next-line:rxjs-finnish
const requests$ = cold('ab|', { a: putRequest$, b: putRequest2$ });
const requests$ = cold('ab|', {
a: putRequest$,
b: putRequest2$,
});
expectObservable(
requests$.pipe(
......@@ -326,7 +176,10 @@ describe('cache.service', () => {
describe('.getAll()', () => {
it('should provide the returned value', inject([ResourceCache], (service: ResourceCache) => {
const values = {
a: { 'hydra:member': [VALUES.a, VALUES.d], 'hydra:totalItems': 2 },
a: {
'hydra:member': [VALUES.a, VALUES.d],
'hydra:totalItems': 2,
},
};
scheduler.withValues(values).run(({ cold, expectObservable }) => {
const getAllRequest$ = cold('a|');
......@@ -368,11 +221,10 @@ describe('cache.service', () => {
b: () => service.get(MY_IRI, () => getRequest$),
});
expectObservable(
requests$.pipe(mergeMap((sendRequest: () => Observable<any>) => sendRequest())),
).toBe('ha|');
expectObservable(requests$.pipe(mergeMap((sendRequest: () => Observable<any>) => sendRequest()))).toBe(
'ha|',
);
});
}));
});
});
});
import { HttpResponseBase } from '@angular/common/http';
import * as _ from 'lodash';
import { Observable, of, race, Subject, throwError } from 'rxjs';
import { map, switchMap, take, tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { map, switchMap, tap } from 'rxjs/operators';
import {
AbstractResourceCache,
......@@ -11,75 +10,9 @@ import {
IRI,
IRI_PROPERTY,
Resource,
} from '../../shared/models';
import { safeForkJoin } from '../../shared/rxjs';
export class APICacheError extends Error {}
export class MissingIRIError extends APICacheError {
public constructor() {
super(`resource must have an ${IRI_PROPERTY} property`);
}
}
export class IRIMismatchError extends APICacheError {
public constructor(expected: any, actual: any) {
super(`${IRI_PROPERTY}s mismatch: ${actual} !== ${expected}`);
}
}
/**
* ValueHolder gère les requêtes d'une seule ressource.
*
* @internal
*/
export class ValueHolder<R extends Resource> {
private readonly value$ = new Subject<R>();
private readonly value = {} as R;
private version = 0;
constructor(private readonly iri: IRI<R>) {}
public set(value: R): Observable<R> {
if (!(IRI_PROPERTY in value)) {
return throwError(new MissingIRIError());
}
if (value[IRI_PROPERTY] !== this.iri) {
return throwError(new IRIMismatchError(this.iri, value[IRI_PROPERTY]));
}
_.assign(this.value, value);
_(this.value)
.keys()
.difference(_.keys(value))
.forEach((key) => delete this.value[key]);
this.version++;
this.value$.next(this.value);
return of(this.value);
}
public listen(queryFactory: () => Observable<R>): Observable<R> {
if (this.version > 0) {
return of(this.value);
}
return this.update(queryFactory());
}
public update(request$: Observable<R>): Observable<R> {
return race(this.value$.pipe(take(1)), request$.pipe(switchMap((item: R) => this.set(item))));
}
public invalidate(): void {
this.version = 0;
}
public delete(): void {
this.value$.complete();
}
}
} from '../types';
import { ValueHolder } from './value-holder';
/**
* Implémentation d'un cache de resource.
*
......@@ -123,10 +56,11 @@ export class ResourceCache extends AbstractResourceCache {
public delete<R extends Resource>(iri: IRI<R>, query$: Observable<HttpResponseBase>): Observable<HttpResponseBase> {
return query$.pipe(
tap(() => {
if (!this.holders.has(iri)) {
return;
const holder = this.holders.get(iri);
if (holder) {
this.holders.delete(iri);
holder.delete();
}
this.holders.get(iri).delete();
this.holders.delete(iri);
}),
);
......@@ -141,7 +75,11 @@ export class ResourceCache extends AbstractResourceCache {
const members = getCollectionMembers(coll);
const memberObservables$ = members.map((item) => this.received(item));
return safeForkJoin(memberObservables$).pipe(
map((items) => Object.assign({} as Collection<R>, coll, { [COLLECTION_MEMBERS]: items })),
map((items) =>
Object.assign({} as Collection<R>, coll, {
[COLLECTION_MEMBERS]: items,
}),
),
);
}),
);
......@@ -151,17 +89,17 @@ export class ResourceCache extends AbstractResourceCache {
* Invalide la valeur d'une IRI pour forcer une mise-à-jour.
*/
public invalidate<R extends Resource>(iri: IRI<R>): void {
if (!this.holders.has(iri)) {
return;
const holder = this.holders.get(iri);
if (holder) {
holder.invalidate();
}
this.holders.get(iri).invalidate();
}
/**
* Retourne le ValueHolder d'une IRI, ou le crée si nécessaire.
*/
private getHolder<R extends Resource>(iri: IRI<R>): ValueHolder<R> {
let holder = this.holders.get(iri) as ValueHolder<R>;
let holder = this.holders.get(iri) as ValueHolder<R> | undefined;
if (!holder) {
holder = new ValueHolder<R>(iri);
this.holders.set(iri, holder);
......
import { IRI_PROPERTY } from '../types';
export class APICacheError extends Error {}
export class MissingIRIError extends APICacheError {
public constructor() {
super(`resource must have an ${IRI_PROPERTY} property`);
}
}
export class IRIMismatchError extends APICacheError {
public constructor(expected: string, actual: string) {
super(`${IRI_PROPERTY}s mismatch: ${actual} !== ${expected}`);
}
}
export * from './cache.service';
export * from './errors';
import { forkJoin } from 'rxjs';
import { IRI, IRI_PROPERTY, Resource } from '../types';
interface MyResource extends Resource {
readonly '@id': IRI<MyResource>;
readonly '@type': 'MyResource';
value: string;
value2?: string;
}
function iri(x: string): IRI<MyResource> {
return x as any;
}
const MY_IRI = iri('/bla/a');
const OTHER_IRI = iri('/bla/B');
const VALUES: { [name: string]: MyResource } = {
a: { '@id': MY_IRI, '@type': 'MyResource', value: 'foo' },
b: { '@id': MY_IRI, '@type': 'MyResource', value: 'bar' },
c: {
'@id': MY_IRI,
'@type': 'MyResource',
value: 'bar',
value2: 'quz',
},
d: { '@id': OTHER_IRI, '@type': 'MyResource', value: 'zig' },
};
let scheduler: MarbleTestScheduler<any>;
beforeEach(() => {
scheduler = MarbleTestScheduler.create(VALUES, 'error');
});
describe('ValueHolder', () => {
let holder: ValueHolder<any>;
beforeEach(() => {
holder = new ValueHolder<MyResource>(iri('/bla/a'));
});
it('should be created', () => {
expect(holder).toBeTruthy();
});
describe('.set()', () => {
function testSet({ value, error, SET_M }: any) {
scheduler.withError(error).run(({ expectObservable }) => {
expectObservable(holder.set(value)).toBe(SET_M);
});
}
it('should provide the value', () =>
testSet({
value: VALUES.a,
SET_M: '(a|)',
}));
it(`should refuse value without ${IRI_PROPERTY}`, () =>
testSet({
value: {},
error: new MissingIRIError(),
SET_M: '#',
}));
it('should refuse value with different @id', () =>
testSet({
value: { '@id': iri('bar') },
error: new IRIMismatchError(MY_IRI, iri('bar')),
SET_M: '#',
}));
it('should always points to the same instance', () => {
forkJoin(holder.set(VALUES.a), holder.set(VALUES.b)).subscribe(([a, b]: MyResource[]) => {
expect(a).toBe(b);
});
});
});
describe('.update()', () => {
it('should provide the value from the server', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ_M = '---a|';
const UPD_M = '--(a|) ';
const request$ = cold(REQ_M);
expectObservable(holder.update(request$)).toBe(UPD_M);
}));
it('should cancel pending requests', () => {
const LOCAL_VALUES = {
a: VALUES.a,
b: VALUES.b,
j: [VALUES.b, VALUES.b],
};
const REQ1_M = '---a|';
const REQ2_M = 'b| ';
const UPDA_M = '(j|) ';
const REQ1_S = '(^!) ';
const REQ2_S = '(^!) ';
scheduler.withValues(LOCAL_VALUES).run(({ cold, expectObservable, expectSubscriptions }) => {
const request1$ = cold(REQ1_M);
const request2$ = cold(REQ2_M);
expectObservable(
safeForkJoin([
//
holder.update(request1$),
holder.update(request2$),
]),
).toBe(UPDA_M);
expectSubscriptions(request1$.subscriptions).toBe(REQ1_S);
expectSubscriptions(request2$.subscriptions).toBe(REQ2_S);
});
});
it('should propagate errors', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ_M = '#';
const UPD_M = '#';
const request$ = cold(REQ_M);
expectObservable(holder.update(request$)).toBe(UPD_M);
}));
it('should restart on errors', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ1_M = '#';
const UPD1_M = '#';
const obs$ = holder.update(cold(REQ1_M));
expectObservable(obs$).toBe(UPD1_M);
const REQ2_M = '-a|';
const UPD2_M = '-a|';
const obs2$ = holder.update(cold(REQ2_M));
expectObservable(obs2$).toBe(UPD2_M);
}));
});
describe('.listen()', () => {
function testListen({ REQUEST_M, LISTEN_M, initial }: any) {
scheduler.run(({ cold, expectObservable }) => {
if (initial) {
holder.set(initial);
}
expectObservable(holder.listen(() => cold(REQUEST_M))).toBe(LISTEN_M);
});
}
it('should provide the value', () =>
testListen({
initial: VALUES.a,
REQUEST_M: /**/ ' ',
LISTEN_M: /***/ '(a|)',
}));
it('should cache the value', () =>
testListen({
initial: VALUES.a,
REQUEST_M: /**/ 'b| ',
LISTEN_M: /***/ '(a|)',
}));