Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/1564 - Add poller for app updates #2204

Merged
merged 8 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:
command: ./node_modules/.bin/eslint "src/**/*.ts" --max-warnings=0
working_directory: ~/project/front-end/
- run:
name: 'Run Prettier with project configuration'
name: "Run Prettier with project configuration"
command: npm run prettier:check:ci
working_directory: ~/project/front-end/
test:
Expand Down
26,262 changes: 14,944 additions & 11,318 deletions front-end/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions front-end/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<div>
<app-poller></app-poller>
<router-outlet></router-outlet>
<p-confirmDialog></p-confirmDialog>
<p-toast></p-toast>
Expand Down
Empty file.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BehaviorSubject, Observable } from 'rxjs';
import { PollerComponent } from './poller.component';
import { Location } from '@angular/common';
import { PollerService } from 'app/shared/services/poller.service';

describe('PollerComponent', () => {
let component: PollerComponent;
let fixture: ComponentFixture<PollerComponent>;
let pollerServiceMock: {
startPolling: jasmine.Spy;
stopPolling: jasmine.Spy;
isNewVersionAvailable$: Observable<boolean>;
};
let locationMock: { path: jasmine.Spy };
let isNewVersionAvailableSubject: BehaviorSubject<boolean>;

beforeEach(async () => {
isNewVersionAvailableSubject = new BehaviorSubject<boolean>(false);

// Mocking PollerService
pollerServiceMock = {
startPolling: jasmine.createSpy('startPolling'),
stopPolling: jasmine.createSpy('stopPolling'),
isNewVersionAvailable$: isNewVersionAvailableSubject.asObservable(),
};

// Mocking Location
locationMock = {
path: jasmine.createSpy('path').and.returnValue('/current-path'),
};

await TestBed.configureTestingModule({
declarations: [PollerComponent],
providers: [
{ provide: PollerService, useValue: pollerServiceMock },
{ provide: Location, useValue: locationMock },
],
}).compileComponents();

fixture = TestBed.createComponent(PollerComponent);
component = fixture.componentInstance;
});

it('should create the component', () => {
expect(component).toBeTruthy();
});

it('should call reload when new version', () => {
spyOn(component, 'reload');

// Simulate new version being available
isNewVersionAvailableSubject.next(true);

fixture.detectChanges();
expect(component['reload']).toHaveBeenCalled();
});

it('should stop polling when component is destroyed', () => {
spyOn(component, 'stopPolling').and.callThrough();

component.ngOnDestroy();

expect(component.stopPolling).toHaveBeenCalled();
expect(pollerServiceMock.stopPolling).toHaveBeenCalled();
});
});
48 changes: 48 additions & 0 deletions front-end/src/app/shared/components/poller/poller.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { PollerService } from 'app/shared/services/poller.service';
import { Subscription } from 'rxjs';
import { Location } from '@angular/common';

@Component({
selector: 'app-poller',
templateUrl: './poller.component.html',
styleUrl: './poller.component.scss',
})
export class PollerComponent implements OnInit, OnDestroy {
private subscription!: Subscription;

constructor(
private pollerService: PollerService,
private location: Location,
) {}

ngOnInit() {
const currentUrl = window.location.href;
const index = currentUrl.indexOf(this.location.path());

let deploymentUrl = index === 0 ? currentUrl : currentUrl.substring(0, index);
deploymentUrl += deploymentUrl.endsWith('/') ? 'index.html' : '/index.html';

this.pollerService.startPolling(deploymentUrl);
this.subscription = this.pollerService.isNewVersionAvailable$.subscribe((isNewVersionAvailable) => {
if (isNewVersionAvailable) {
this.reload();
}
});
}

reload() {
window.location.reload();
}

ngOnDestroy() {
this.stopPolling();
}

stopPolling() {
this.pollerService.stopPolling();
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
84 changes: 84 additions & 0 deletions front-end/src/app/shared/services/poller.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { discardPeriodicTasks, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { PollerService } from './poller.service';

describe('PollerService', () => {
let service: PollerService;
let httpMock: HttpTestingController;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [PollerService],
});
service = TestBed.inject(PollerService);
httpMock = TestBed.inject(HttpTestingController);
});

afterEach(() => {
httpMock.verify();
});

it('should be created', () => {
expect(service).toBeTruthy();
});

it('should start polling and call compareVersions', fakeAsync(() => {
const compareVersionsSpy = spyOn(service, 'compareVersions').and.callFake(() => Promise.resolve());

service.startPolling('test-url');

// Fast-forward time to simulate the interval
tick(5000);

expect(compareVersionsSpy).toHaveBeenCalled();

// Discard the periodic task (interval)
discardPeriodicTasks();
}));

it('should stop polling when stopPolling is called', () => {
service.startPolling('test-url');
service.stopPolling();

// Assuming versionCheckSubscription is set to public for testing purposes
expect(service.versionCheckSubscription?.closed).toBe(true);
});

it('should detect new version available', fakeAsync(() => {
const mockHtmlResponse = `
<html>
<head>
<script src="main.abc123.js" type="module"></script>
</head>
</html>`;

spyOn(document, 'getElementsByTagName').and.returnValue([
{
src: 'http://localhost/main.abc122.js',
},
] as unknown as HTMLCollectionOf<Element>);

service.compareVersions('test-url');

const req = httpMock.expectOne('test-url');
req.flush(mockHtmlResponse, { status: 200, statusText: 'OK' });

tick(); // Fast-forward any pending asynchronous tasks

service.isNewVersionAvailable$.subscribe((isAvailable) => {
expect(isAvailable).toBeTrue();
});
}));

it('should handle error in version check', async () => {
service.compareVersions('test-url');

const req = httpMock.expectOne('test-url');
req.error(new ErrorEvent('Network error'), { status: 500 });

service.isNewVersionAvailable$.subscribe((isAvailable) => {
expect(isAvailable).toBeFalse();
});
});
});
57 changes: 57 additions & 0 deletions front-end/src/app/shared/services/poller.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, firstValueFrom, interval, Subscription, switchMap } from 'rxjs';

@Injectable({
providedIn: 'root',
})
export class PollerService {
private isNewVersionAvailable = new BehaviorSubject<boolean>(false);
isNewVersionAvailable$ = this.isNewVersionAvailable.asObservable();
versionCheckSubscription?: Subscription;
constructor(private http: HttpClient) {}

startPolling(deploymentUrl: string) {
this.versionCheckSubscription = interval(5000)
.pipe(switchMap(() => this.compareVersions(deploymentUrl)))
.subscribe();
}

async compareVersions(deploymentUrl: string) {
try {
const fetchedPage = await firstValueFrom(this.http.get(deploymentUrl, { responseType: 'text' }));
const loadedText = fetchedPage as string;
const mainScriptRegex = /<script\s+src="(main\.[^"]+\.js)"\s+type="module"><\/script>/gim;
const matchResponses = mainScriptRegex.exec(loadedText);
const remoteMainScript = matchResponses && matchResponses.length > 0 ? matchResponses[1] : undefined;

if (!remoteMainScript) {
console.log('Could not find main script in index.html');
this.isNewVersionAvailable.next(false);
return;
}

const scriptTags = document.getElementsByTagName('script');
let currentMainScript: string | undefined = undefined;
for (let i = 0; i < scriptTags.length; i++) {
const scriptTag = scriptTags[i];
const match = /^.*\/(main.*\.js).*$/gim.exec(scriptTag.src);
if (match) {
currentMainScript = match[1];
break;
}
}

this.isNewVersionAvailable.next(
!!currentMainScript && !!remoteMainScript && currentMainScript !== remoteMainScript,
);
} catch (error) {
console.error('Error fetching deployment URL', error);
this.isNewVersionAvailable.next(false);
}
}

stopPolling() {
this.versionCheckSubscription?.unsubscribe();
}
}
3 changes: 3 additions & 0 deletions front-end/src/app/shared/shared.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import { DownloadTrayComponent } from './components/download-tray/download-tray.
import { SidebarModule } from 'primeng/sidebar';
import { InputNumberComponent } from './components/inputs/input-number/input-number.component';
import { SaveCancelComponent } from './components/save-cancel/save-cancel.component';
import { PollerComponent } from './components/poller/poller.component';
import { CalendarComponent } from './components/calendar/calendar.component';

@NgModule({
Expand Down Expand Up @@ -141,6 +142,7 @@ import { CalendarComponent } from './components/calendar/calendar.component';
DownloadTrayComponent,
InputNumberComponent,
SaveCancelComponent,
PollerComponent,
CalendarComponent,
],
exports: [
Expand Down Expand Up @@ -185,6 +187,7 @@ import { CalendarComponent } from './components/calendar/calendar.component';
DownloadTrayComponent,
InputNumberComponent,
SaveCancelComponent,
PollerComponent,
CalendarComponent,
],
providers: [DatePipe, CurrencyPipe],
Expand Down
4 changes: 3 additions & 1 deletion tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ def _do_deploy(ctx, space):
print("\n")
cmd = "push --strategy rolling" if existing_deploy.ok else "push"
new_deploy = ctx.run(
f"cf {cmd} {APP_NAME} -f {manifest_filename}", echo=True, warn=True,
f"cf {cmd} {APP_NAME} -f {manifest_filename}",
echo=True,
warn=True,
)

os.chdir(orig_directory)
Expand Down