systemInfo.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import $ from "jquery"
  2. import { SystemInfoDescription, SystemInfo as ModelSystemInfo, HostnameLiveSystemInfoDescription } from "../../src/models/systemInfo";
  3. import { HostnameServiceDescription } from "../../src/models/service";
  4. export interface TimedLiveSystemInfo {
  5. time: Date;
  6. data: HostnameLiveSystemInfoDescription;
  7. }
  8. export namespace DAL {
  9. export class SystemInfo {
  10. private static lastCachedData: SystemInfoDescription|null = null;
  11. private static liveData: TimedLiveSystemInfo[] = [];
  12. private static liveHandler: ReturnType<typeof setTimeout>|boolean = false;
  13. private static getData(): Promise<void> {
  14. return new Promise(ok => {
  15. $.get("/api/sysinfo", response => {
  16. this.lastCachedData = response;
  17. ok();
  18. });
  19. });
  20. }
  21. private static getDataWithCache(): Promise<void> {
  22. if (this.lastCachedData)
  23. return Promise.resolve();
  24. return this.getData();
  25. }
  26. public static async getInfo(hostname: string): Promise<ModelSystemInfo|undefined> {
  27. await this.getDataWithCache();
  28. return this.lastCachedData?.systemInfo[hostname];
  29. }
  30. public static async listHosts(): Promise<Array<string>> {
  31. await this.getDataWithCache();
  32. return Object.keys(this.lastCachedData?.systemInfo ?? {});
  33. }
  34. private static pushLiveData(data: HostnameLiveSystemInfoDescription): TimedLiveSystemInfo {
  35. let result: TimedLiveSystemInfo = { data: data, time: new Date() };
  36. this.liveData.push(result);
  37. return result;
  38. }
  39. private static pollNow(): Promise<TimedLiveSystemInfo> {
  40. return new Promise(ok => {
  41. $.get("/api/sysinfo/live", response => {
  42. ok(this.pushLiveData(response.liveSystemInfo));
  43. });
  44. });
  45. }
  46. private static async pollTick(): Promise<TimedLiveSystemInfo> {
  47. let result = await this.pollNow();
  48. this.liveHandler = setTimeout(this.pollTick.bind(this), 10000);
  49. return result;
  50. }
  51. public static async startLivePolling(): Promise<TimedLiveSystemInfo> {
  52. if (this.liveHandler !== false)
  53. return this.liveData[this.liveData.length-1]!;
  54. this.liveHandler = true;
  55. await this.getDataWithCache();
  56. return await this.pollTick();
  57. }
  58. public static async getLive(): Promise<TimedLiveSystemInfo> {
  59. return await this.startLivePolling();
  60. }
  61. public static async getServices(): Promise<HostnameServiceDescription> {
  62. return new Promise(ok => {
  63. $.get("/api/services/list", response => {
  64. ok(response.services);
  65. });
  66. });
  67. }
  68. }
  69. }