308 lines
12 KiB
TypeScript
308 lines
12 KiB
TypeScript
import { Injectable, NgZone, OnDestroy } from '@angular/core';
|
|
import {
|
|
HubConnection,
|
|
HubConnectionBuilder,
|
|
HubConnectionState,
|
|
IRetryPolicy,
|
|
LogLevel,
|
|
RetryContext
|
|
} from '@microsoft/signalr';
|
|
import { BehaviorSubject, Observable, Subject, Subscription, filter, map } from 'rxjs';
|
|
import { environment } from 'src/environments/environment';
|
|
import { ApiService } from '../../app.api.service';
|
|
import { AuthService } from '../auth/auth.service';
|
|
import { JobSnapshot, isJobFinished } from '../../_models/realtime/job-snapshot';
|
|
|
|
export type RealtimeConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
|
|
|
|
/** A message pushed with IAppClient.Event on the server. */
|
|
export interface RealtimeEvent<T = any> {
|
|
topic: string;
|
|
payload: T;
|
|
}
|
|
|
|
/**
|
|
* Retries quickly at first, then every 30 s for as long as the user is signed in.
|
|
* Gives up (null) once there is no token any more - a signed-out tab must not keep knocking.
|
|
*/
|
|
class SignedInRetryPolicy implements IRetryPolicy {
|
|
private static readonly steps = [0, 2000, 5000, 10000, 20000];
|
|
|
|
nextRetryDelayInMilliseconds(context: RetryContext): number | null {
|
|
if (!ApiService.AuthenticationToken && !localStorage.getItem('token')) {
|
|
return null;
|
|
}
|
|
const steps = SignedInRetryPolicy.steps;
|
|
return context.previousRetryCount < steps.length ? steps[context.previousRetryCount] : 30000;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The app's ONE SignalR connection (hub HRM.UI/Realtime/AppHub.cs at /api/hubs/app), shared by every feature.
|
|
*
|
|
* - Lazy: nothing connects until a feature asks (watchJob / on), so screens that never use it pay nothing.
|
|
* - Auth is the HttpOnly JWToken cookie the API already uses (same origin, sent automatically). No token in the URL.
|
|
* - Reconnects by itself; a new sign-in / payroll-type switch (new token) opens a fresh connection.
|
|
* - Signs out with the user (AuthService.logout$).
|
|
*
|
|
* Features use:
|
|
* watchJob(runId) - live progress of a background job (HRM.UI/Realtime/Jobs), with HTTP catch-up and fallback.
|
|
* on(topic) - any other server push (IRealtimePublisher.ToUserAsync / ToPayrollTypeAsync / ToAllAsync).
|
|
*/
|
|
@Injectable({ providedIn: 'root' })
|
|
export class RealtimeService implements OnDestroy {
|
|
private static readonly HUB_PATH = '/hubs/app';
|
|
/** While connected, a job with no message for this long is re-read over HTTP (a lost message can never freeze the bar). */
|
|
private static readonly SILENCE_CHECK_MS = 15000;
|
|
/** Polling interval when no connection can be made at all. */
|
|
private static readonly POLL_MS = 2000;
|
|
|
|
private connection: HubConnection | null = null;
|
|
private connectedToken: string | null = null;
|
|
private startPromise: Promise<boolean> | null = null;
|
|
|
|
private readonly stateSubject = new BehaviorSubject<RealtimeConnectionState>('disconnected');
|
|
private readonly jobProgress$ = new Subject<JobSnapshot>();
|
|
private readonly events$ = new Subject<RealtimeEvent>();
|
|
/** A (re)connection was made: joined groups are gone and must be joined again. */
|
|
private readonly resubscribe$ = new Subject<void>();
|
|
private readonly subscriptions = new Subscription();
|
|
|
|
/** Current connection state, e.g. for a small "live" indicator. */
|
|
readonly state$: Observable<RealtimeConnectionState> = this.stateSubject.asObservable();
|
|
|
|
constructor(private zone: NgZone, private apiService: ApiService, authService: AuthService) {
|
|
this.subscriptions.add(authService.logout$.subscribe(() => this.stop()));
|
|
}
|
|
|
|
ngOnDestroy(): void {
|
|
this.subscriptions.unsubscribe();
|
|
this.stop();
|
|
}
|
|
|
|
get isConnected(): boolean {
|
|
return this.connection?.state === HubConnectionState.Connected;
|
|
}
|
|
|
|
/**
|
|
* Makes sure the connection is up with the current sign-in. Resolves true when connected, false when it could not
|
|
* connect (callers then fall back to HTTP). Never rejects.
|
|
*/
|
|
connect(): Promise<boolean> {
|
|
const token = ApiService.AuthenticationToken || localStorage.getItem('token');
|
|
if (!token) {
|
|
return Promise.resolve(false);
|
|
}
|
|
|
|
// Signed in again or switched payroll type: the old connection carries the old claims.
|
|
if (this.connection && this.connectedToken !== token) {
|
|
this.dropConnection();
|
|
}
|
|
|
|
if (this.connection) {
|
|
if (this.connection.state === HubConnectionState.Connected) {
|
|
return Promise.resolve(true);
|
|
}
|
|
if (this.startPromise) {
|
|
return this.startPromise;
|
|
}
|
|
if (this.connection.state === HubConnectionState.Reconnecting) {
|
|
return Promise.resolve(false);
|
|
}
|
|
} else {
|
|
this.connection = this.buildConnection();
|
|
this.connectedToken = token;
|
|
}
|
|
|
|
const connection = this.connection;
|
|
this.setState('connecting');
|
|
const startPromise: Promise<boolean> = connection.start()
|
|
.then(() => {
|
|
if (this.connection !== connection) {
|
|
return false; // signed out / replaced while starting
|
|
}
|
|
this.setState('connected');
|
|
this.zone.run(() => this.resubscribe$.next());
|
|
return true;
|
|
})
|
|
.catch((err) => {
|
|
if (!environment.production) {
|
|
console.warn('[realtime] could not connect, HTTP fallback is used', err);
|
|
}
|
|
if (this.connection === connection) {
|
|
this.setState('disconnected');
|
|
}
|
|
return false;
|
|
})
|
|
.finally(() => {
|
|
if (this.startPromise === startPromise) {
|
|
this.startPromise = null;
|
|
}
|
|
});
|
|
this.startPromise = startPromise;
|
|
return startPromise;
|
|
}
|
|
|
|
/** Closes the connection (sign-out). Watchers keep working over HTTP until they finish. */
|
|
stop(): void {
|
|
this.dropConnection();
|
|
}
|
|
|
|
/**
|
|
* Server pushes of one topic (sent with IRealtimePublisher.ToUserAsync / ToPayrollTypeAsync / ToAllAsync).
|
|
* Subscribing connects if needed.
|
|
*/
|
|
on<T = any>(topic: string): Observable<T> {
|
|
return new Observable<T>((subscriber) => {
|
|
this.connect();
|
|
const sub = this.events$
|
|
.pipe(filter((e) => e.topic === topic), map((e) => e.payload as T))
|
|
.subscribe(subscriber);
|
|
return () => sub.unsubscribe();
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Live state of a background job, from its current state to its end (the observable completes when the job
|
|
* has Succeeded or Failed). Works the same after a page reload, in a second tab and on a flaky network:
|
|
* it joins the job over SignalR, re-joins after every reconnect, re-reads over HTTP when the push goes quiet,
|
|
* and polls over HTTP if no connection can be made at all. Out-of-date messages are dropped by sequence.
|
|
*/
|
|
watchJob(runId: string): Observable<JobSnapshot> {
|
|
return new Observable<JobSnapshot>((subscriber) => {
|
|
let last: JobSnapshot | null = null;
|
|
let lastMessageAt = Date.now();
|
|
let closed = false;
|
|
let pollTimer: any = null;
|
|
let fetching = false;
|
|
|
|
const emit = (job: JobSnapshot | null | undefined) => {
|
|
if (closed || !job || job.runId !== runId) {
|
|
return;
|
|
}
|
|
lastMessageAt = Date.now();
|
|
if (last && job.sequence <= last.sequence) {
|
|
return;
|
|
}
|
|
last = job;
|
|
subscriber.next(job);
|
|
if (isJobFinished(job)) {
|
|
finish();
|
|
subscriber.complete();
|
|
}
|
|
};
|
|
|
|
const fetchOnce = () => {
|
|
if (closed || fetching) {
|
|
return;
|
|
}
|
|
fetching = true;
|
|
this.apiService.httpGet<JobSnapshot>('/jobs/' + encodeURIComponent(runId)).subscribe({
|
|
next: (job) => {
|
|
fetching = false;
|
|
emit(job);
|
|
},
|
|
error: (err) => {
|
|
fetching = false;
|
|
if (err?.status === 404 || err?.status === 403) {
|
|
finish();
|
|
subscriber.error(new Error(typeof err?.error === 'string' ? err.error : 'The job could not be found.'));
|
|
}
|
|
// other errors (network blip): the next tick tries again
|
|
}
|
|
});
|
|
};
|
|
|
|
const joinOverHub = () => {
|
|
if (closed || !this.connection || !this.isConnected) {
|
|
return;
|
|
}
|
|
this.connection.invoke<JobSnapshot>('SubscribeJob', runId)
|
|
.then((job) => this.zone.run(() => emit(job)))
|
|
.catch(() => this.zone.run(() => fetchOnce()));
|
|
};
|
|
|
|
// One timer does both jobs: polling when there is no connection, a silence check when there is.
|
|
const tick = () => {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
if (!this.isConnected || Date.now() - lastMessageAt >= RealtimeService.SILENCE_CHECK_MS) {
|
|
fetchOnce();
|
|
}
|
|
};
|
|
|
|
const subs = new Subscription();
|
|
subs.add(this.jobProgress$.pipe(filter((j) => j.runId === runId)).subscribe((j) => emit(j)));
|
|
subs.add(this.resubscribe$.subscribe(() => joinOverHub()));
|
|
|
|
const finish = () => {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
closed = true;
|
|
subs.unsubscribe();
|
|
if (pollTimer) {
|
|
clearInterval(pollTimer);
|
|
pollTimer = null;
|
|
}
|
|
if (this.connection && this.isConnected) {
|
|
this.connection.invoke('UnsubscribeJob', runId).catch(() => { /* connection going away */ });
|
|
}
|
|
};
|
|
|
|
pollTimer = setInterval(tick, RealtimeService.POLL_MS);
|
|
this.connect().then((ok) => {
|
|
if (ok) {
|
|
joinOverHub(); // connect() may already have emitted resubscribe$ - a second join is harmless
|
|
} else {
|
|
fetchOnce();
|
|
}
|
|
});
|
|
|
|
return () => finish();
|
|
});
|
|
}
|
|
|
|
private buildConnection(): HubConnection {
|
|
const connection = new HubConnectionBuilder()
|
|
.withUrl(ApiService.BASE_URL + RealtimeService.HUB_PATH, { withCredentials: true })
|
|
.withAutomaticReconnect(new SignedInRetryPolicy())
|
|
.configureLogging(environment.production ? LogLevel.Warning : LogLevel.Information)
|
|
.build();
|
|
|
|
// Server -> browser methods: the names of HRM.UI/Realtime/IAppClient.cs.
|
|
connection.on('JobProgress', (job: JobSnapshot) => this.zone.run(() => this.jobProgress$.next(job)));
|
|
connection.on('Event', (topic: string, payload: any) => this.zone.run(() => this.events$.next({ topic, payload })));
|
|
|
|
connection.onreconnecting(() => this.setState('reconnecting'));
|
|
connection.onreconnected(() => {
|
|
this.setState('connected');
|
|
this.zone.run(() => this.resubscribe$.next());
|
|
});
|
|
connection.onclose(() => {
|
|
if (this.connection === connection) {
|
|
this.setState('disconnected');
|
|
}
|
|
});
|
|
return connection;
|
|
}
|
|
|
|
private dropConnection(): void {
|
|
const connection = this.connection;
|
|
this.connection = null;
|
|
this.connectedToken = null;
|
|
this.startPromise = null;
|
|
this.setState('disconnected');
|
|
if (connection) {
|
|
connection.stop().catch(() => { /* already closed */ });
|
|
}
|
|
}
|
|
|
|
private setState(state: RealtimeConnectionState): void {
|
|
if (this.stateSubject.value !== state) {
|
|
this.zone.run(() => this.stateSubject.next(state));
|
|
}
|
|
}
|
|
}
|