@seedtactics/insight-client 17.0.1-beta.9 → 17.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +16 -4
  2. package/dist/assets/ProgramHighlight-mKbZxoXO.js +3 -0
  3. package/dist/assets/index-Cjt4dPv7.js +367 -0
  4. package/dist/cell-status/current-status.d.ts +1 -0
  5. package/dist/cell-status/current-status.js +46 -51
  6. package/dist/cell-status/loading.d.ts +13 -2
  7. package/dist/cell-status/loading.js +39 -7
  8. package/dist/cell-status/material-details.d.ts +2 -2
  9. package/dist/cell-status/material-details.js +33 -14
  10. package/dist/components/App.d.ts +0 -5
  11. package/dist/components/App.js +1 -1
  12. package/dist/components/ChooseMode.js +15 -3
  13. package/dist/components/ErrorsAndLoading.js +2 -1
  14. package/dist/components/LoadingIcon.js +3 -1
  15. package/dist/components/analysis/BufferChart.js +3 -2
  16. package/dist/components/operations/AllMaterial.js +9 -12
  17. package/dist/components/operations/RecentCycleChart.js +16 -21
  18. package/dist/components/quality/QualityMaterial.js +3 -12
  19. package/dist/components/station-monitor/BasketLoadStationWork.d.ts +4 -7
  20. package/dist/components/station-monitor/BasketLoadStationWork.js +97 -44
  21. package/dist/components/station-monitor/CancelLoadButton.js +8 -3
  22. package/dist/components/station-monitor/InvalidateCycle.js +26 -25
  23. package/dist/components/station-monitor/LoadStation.d.ts +0 -5
  24. package/dist/components/station-monitor/LoadStation.js +88 -115
  25. package/dist/components/station-monitor/Material.d.ts +6 -1
  26. package/dist/components/station-monitor/Material.js +22 -9
  27. package/dist/components/station-monitor/MoveMaterialArrows.js +9 -0
  28. package/dist/components/station-monitor/PrintedLabel.js +15 -19
  29. package/dist/components/station-monitor/QuarantineButton.js +21 -29
  30. package/dist/components/station-monitor/QueuesAddMaterial.js +2 -5
  31. package/dist/components/station-monitor/SystemOverview.js +59 -19
  32. package/dist/components/station-monitor/Whiteboard.js +14 -15
  33. package/dist/data/material-operation-policy.d.ts +6 -0
  34. package/dist/data/material-operation-policy.js +26 -2
  35. package/dist/data/move-arrows.d.ts +7 -0
  36. package/dist/data/move-arrows.js +107 -24
  37. package/dist/data/queue-material.d.ts +1 -0
  38. package/dist/data/queue-material.js +55 -48
  39. package/dist/extension.d.ts +1 -1
  40. package/dist/extension.js +1 -0
  41. package/dist/index.html +2 -39
  42. package/dist/index.js +1 -6
  43. package/dist/network/api-errors.d.ts +8 -0
  44. package/dist/network/api-errors.js +77 -0
  45. package/dist/network/api.d.ts +20 -34
  46. package/dist/network/api.js +68 -64
  47. package/dist/network/backend-mock.js +3 -0
  48. package/dist/network/backend.d.ts +3 -2
  49. package/dist/network/current-status-session.d.ts +27 -0
  50. package/dist/network/current-status-session.js +65 -0
  51. package/dist/network/websocket.d.ts +4 -0
  52. package/dist/network/websocket.js +176 -37
  53. package/dist/util/parseISODuration.js +10 -9
  54. package/docs/material-quarantine.md +5 -4
  55. package/docs/mazak.md +11 -14
  56. package/docs/operator-procedures.md +14 -0
  57. package/docs/server-config.md +20 -12
  58. package/package.json +25 -20
  59. package/dist/assets/ProgramHighlight-C6zSEXCX.js +0 -3
  60. package/dist/assets/index-MFZreX-b.js +0 -388
  61. package/dist/components/station-monitor/BasketMovementArrival.d.ts +0 -40
  62. package/dist/components/station-monitor/BasketMovementArrival.js +0 -165
@@ -393,6 +393,40 @@ export class JobsClient {
393
393
  }
394
394
  return Promise.resolve(null);
395
395
  }
396
+ completeBasketLoadStation(completion, signal) {
397
+ let url_ = this.baseUrl + "/api/v1/jobs/basket-load-station/complete";
398
+ url_ = url_.replace(/[?&]$/, "");
399
+ const content_ = JSON.stringify(completion);
400
+ let options_ = {
401
+ body: content_,
402
+ method: "POST",
403
+ signal,
404
+ headers: {
405
+ "Content-Type": "application/json",
406
+ },
407
+ };
408
+ return this.http.fetch(url_, options_).then((_response) => {
409
+ return this.processCompleteBasketLoadStation(_response);
410
+ });
411
+ }
412
+ processCompleteBasketLoadStation(response) {
413
+ const status = response.status;
414
+ let _headers = {};
415
+ if (response.headers && response.headers.forEach) {
416
+ response.headers.forEach((v, k) => (_headers[k] = v));
417
+ }
418
+ if (status === 200) {
419
+ return response.text().then((_responseText) => {
420
+ return;
421
+ });
422
+ }
423
+ else if (status !== 200 && status !== 204) {
424
+ return response.text().then((_responseText) => {
425
+ return throwException("An unexpected server error occurred.", status, _responseText, _headers);
426
+ });
427
+ }
428
+ return Promise.resolve(null);
429
+ }
396
430
  currentStatus(signal) {
397
431
  let url_ = this.baseUrl + "/api/v1/jobs/status";
398
432
  url_ = url_.replace(/[?&]$/, "");
@@ -3566,6 +3600,7 @@ export class CurrentStatus {
3566
3600
  }
3567
3601
  init(_data) {
3568
3602
  if (_data) {
3603
+ this.revision = _data["Revision"];
3569
3604
  this.timeOfCurrentStatusUTC = _data["TimeOfCurrentStatusUTC"]
3570
3605
  ? new Date(_data["TimeOfCurrentStatusUTC"].toString())
3571
3606
  : undefined;
@@ -3625,11 +3660,6 @@ export class CurrentStatus {
3625
3660
  : new BasketStatus();
3626
3661
  }
3627
3662
  }
3628
- if (Array.isArray(_data["BasketMoveInstructions"])) {
3629
- this.basketMoveInstructions = [];
3630
- for (let item of _data["BasketMoveInstructions"])
3631
- this.basketMoveInstructions.push(BasketMoveInstruction.fromJS(item));
3632
- }
3633
3663
  this.customState = _data["CustomState"];
3634
3664
  }
3635
3665
  }
@@ -3641,6 +3671,7 @@ export class CurrentStatus {
3641
3671
  }
3642
3672
  toJSON(data) {
3643
3673
  data = typeof data === "object" ? data : {};
3674
+ data["Revision"] = this.revision;
3644
3675
  data["TimeOfCurrentStatusUTC"] = this.timeOfCurrentStatusUTC
3645
3676
  ? this.timeOfCurrentStatusUTC.toISOString()
3646
3677
  : undefined;
@@ -3700,11 +3731,6 @@ export class CurrentStatus {
3700
3731
  : undefined;
3701
3732
  }
3702
3733
  }
3703
- if (Array.isArray(this.basketMoveInstructions)) {
3704
- data["BasketMoveInstructions"] = [];
3705
- for (let item of this.basketMoveInstructions)
3706
- data["BasketMoveInstructions"].push(item ? item.toJSON() : undefined);
3707
- }
3708
3734
  data["CustomState"] = this.customState;
3709
3735
  return data;
3710
3736
  }
@@ -4050,6 +4076,7 @@ export class InProcessMaterialAction {
4050
4076
  init(_data) {
4051
4077
  if (_data) {
4052
4078
  this.type = _data["Type"];
4079
+ this.automatedTransfer = _data["AutomatedTransfer"];
4053
4080
  this.workId = _data["WorkId"];
4054
4081
  this.loadCancellationId = _data["LoadCancellationId"];
4055
4082
  this.loadOntoPalletNum = _data["LoadOntoPalletNum"];
@@ -4077,6 +4104,7 @@ export class InProcessMaterialAction {
4077
4104
  toJSON(data) {
4078
4105
  data = typeof data === "object" ? data : {};
4079
4106
  data["Type"] = this.type;
4107
+ data["AutomatedTransfer"] = this.automatedTransfer;
4080
4108
  data["WorkId"] = this.workId;
4081
4109
  data["LoadCancellationId"] = this.loadCancellationId;
4082
4110
  data["LoadOntoPalletNum"] = this.loadOntoPalletNum;
@@ -4365,6 +4393,7 @@ export class BasketStatus {
4365
4393
  init(_data) {
4366
4394
  if (_data) {
4367
4395
  this.basketId = _data["BasketId"];
4396
+ this.slotCount = _data["SlotCount"];
4368
4397
  this.loadStationWork = _data["LoadStationWork"]
4369
4398
  ? BasketLoadStationWork.fromJS(_data["LoadStationWork"])
4370
4399
  : undefined;
@@ -4392,6 +4421,7 @@ export class BasketStatus {
4392
4421
  toJSON(data) {
4393
4422
  data = typeof data === "object" ? data : {};
4394
4423
  data["BasketId"] = this.basketId;
4424
+ data["SlotCount"] = this.slotCount;
4395
4425
  data["LoadStationWork"] = this.loadStationWork
4396
4426
  ? this.loadStationWork.toJSON()
4397
4427
  : undefined;
@@ -4424,6 +4454,7 @@ export class BasketLoadStationWork {
4424
4454
  this.type = _data["Type"];
4425
4455
  this.readyToConfirm = _data["ReadyToConfirm"];
4426
4456
  this.confirmationBlockedReason = _data["ConfirmationBlockedReason"];
4457
+ this.instructionWarning = _data["InstructionWarning"];
4427
4458
  if (Array.isArray(_data["AwaitingMaterialSlots"])) {
4428
4459
  this.awaitingMaterialSlots = [];
4429
4460
  for (let item of _data["AwaitingMaterialSlots"])
@@ -4443,6 +4474,7 @@ export class BasketLoadStationWork {
4443
4474
  data["Type"] = this.type;
4444
4475
  data["ReadyToConfirm"] = this.readyToConfirm;
4445
4476
  data["ConfirmationBlockedReason"] = this.confirmationBlockedReason;
4477
+ data["InstructionWarning"] = this.instructionWarning;
4446
4478
  if (Array.isArray(this.awaitingMaterialSlots)) {
4447
4479
  data["AwaitingMaterialSlots"] = [];
4448
4480
  for (let item of this.awaitingMaterialSlots)
@@ -4495,60 +4527,6 @@ export var BasketLocationEnum;
4495
4527
  BasketLocationEnum["Storage"] = "Storage";
4496
4528
  BasketLocationEnum["InTransit"] = "InTransit";
4497
4529
  })(BasketLocationEnum || (BasketLocationEnum = {}));
4498
- export class BasketMoveInstruction {
4499
- constructor(data) {
4500
- if (data) {
4501
- for (var property in data) {
4502
- if (data.hasOwnProperty(property))
4503
- this[property] = data[property];
4504
- }
4505
- }
4506
- if (!data) {
4507
- this.destination = new BasketPosition();
4508
- }
4509
- }
4510
- init(_data) {
4511
- if (_data) {
4512
- this.instructionId = _data["InstructionId"];
4513
- this.basketId = _data["BasketId"];
4514
- this.source = _data["Source"] ? BasketPosition.fromJS(_data["Source"]) : undefined;
4515
- this.destination = _data["Destination"]
4516
- ? BasketPosition.fromJS(_data["Destination"])
4517
- : new BasketPosition();
4518
- this.reason = _data["Reason"];
4519
- this.displayText = _data["DisplayText"];
4520
- this.prerequisiteInstructionId = _data["PrerequisiteInstructionId"];
4521
- }
4522
- }
4523
- static fromJS(data) {
4524
- data = typeof data === "object" ? data : {};
4525
- let result = new BasketMoveInstruction();
4526
- result.init(data);
4527
- return result;
4528
- }
4529
- toJSON(data) {
4530
- data = typeof data === "object" ? data : {};
4531
- data["InstructionId"] = this.instructionId;
4532
- data["BasketId"] = this.basketId;
4533
- data["Source"] = this.source ? this.source.toJSON() : undefined;
4534
- data["Destination"] = this.destination ? this.destination.toJSON() : undefined;
4535
- data["Reason"] = this.reason;
4536
- data["DisplayText"] = this.displayText;
4537
- data["PrerequisiteInstructionId"] = this.prerequisiteInstructionId;
4538
- return data;
4539
- }
4540
- }
4541
- export var BasketMoveReason;
4542
- (function (BasketMoveReason) {
4543
- BasketMoveReason["LoadMaterial"] = "LoadMaterial";
4544
- BasketMoveReason["UnloadMaterial"] = "UnloadMaterial";
4545
- BasketMoveReason["ProcessTransfer"] = "ProcessTransfer";
4546
- BasketMoveReason["SupplyMaterialToCell"] = "SupplyMaterialToCell";
4547
- BasketMoveReason["SupplyEmptyBasket"] = "SupplyEmptyBasket";
4548
- BasketMoveReason["ReturnToStorage"] = "ReturnToStorage";
4549
- BasketMoveReason["RemoveForCorrection"] = "RemoveForCorrection";
4550
- BasketMoveReason["Other"] = "Other";
4551
- })(BasketMoveReason || (BasketMoveReason = {}));
4552
4530
  export class ProblemDetails {
4553
4531
  constructor(data) {
4554
4532
  if (data) {
@@ -5003,6 +4981,32 @@ export class Rebooking {
5003
4981
  return data;
5004
4982
  }
5005
4983
  }
4984
+ export class BasketLoadStationCompletion {
4985
+ constructor(data) {
4986
+ if (data) {
4987
+ for (var property in data) {
4988
+ if (data.hasOwnProperty(property))
4989
+ this[property] = data[property];
4990
+ }
4991
+ }
4992
+ }
4993
+ init(_data) {
4994
+ if (_data) {
4995
+ this.workId = _data["WorkId"];
4996
+ }
4997
+ }
4998
+ static fromJS(data) {
4999
+ data = typeof data === "object" ? data : {};
5000
+ let result = new BasketLoadStationCompletion();
5001
+ result.init(data);
5002
+ return result;
5003
+ }
5004
+ toJSON(data) {
5005
+ data = typeof data === "object" ? data : {};
5006
+ data["WorkId"] = this.workId;
5007
+ return data;
5008
+ }
5009
+ }
5006
5010
  export class SimulationResults {
5007
5011
  constructor(data) {
5008
5012
  if (data) {
@@ -229,6 +229,9 @@ export function registerMockBackend(offsetSeconds, mockD, mockEvts) {
229
229
  quarantineQueuedMaterial() {
230
230
  return Promise.resolve();
231
231
  },
232
+ completeBasketLoadStation() {
233
+ return Promise.resolve();
234
+ },
232
235
  cancelLoad() {
233
236
  return Promise.resolve();
234
237
  },
@@ -3,7 +3,7 @@ import { User } from "oidc-client-ts";
3
3
  export interface JobAPI {
4
4
  history(startUTC: Date, endUTC: Date): Promise<Readonly<api.IHistoricData>>;
5
5
  recent(startUTC: Date, alreadyKnownSchIds: string[]): Promise<Readonly<api.IRecentHistoricData>>;
6
- currentStatus(): Promise<Readonly<api.ICurrentStatus>>;
6
+ currentStatus(signal?: AbortSignal): Promise<Readonly<api.ICurrentStatus>>;
7
7
  setJobComment(unique: string, comment: string): Promise<void>;
8
8
  removeMaterialFromAllQueues(materialId: number, operatorName: string | undefined): Promise<void>;
9
9
  bulkRemoveMaterialFromQueues(operatorName: string | null, materialIds: ReadonlyArray<number> | null): Promise<void>;
@@ -12,6 +12,7 @@ export interface JobAPI {
12
12
  addUnallocatedCastingToQueue(castingName: string, queue: string, qty: number, operatrorName: string | null, workorder: string | null, serials: string[]): Promise<ReadonlyArray<Readonly<api.IInProcessMaterial>>>;
13
13
  signalMaterialForQuarantine(materialId: number, operName: string | null, reason: string | undefined): Promise<void>;
14
14
  quarantineQueuedMaterial(materialId: number, operName: string | null, reason: string | undefined): Promise<void>;
15
+ completeBasketLoadStation(request: Readonly<api.IBasketLoadStationCompletion>): Promise<void>;
15
16
  cancelLoad(materialId: number, operName: string | null, request: Readonly<api.ICancelLoadRequest>): Promise<void>;
16
17
  invalidatePalletCycle(materialId: number, operName: string | null | undefined, changeCastingTo: string | null | undefined, changeJobUniqueTo: string | null | undefined, process: number): Promise<Readonly<api.IMaterialDetails> | null | undefined>;
17
18
  unscheduledRebookings(signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.IRebooking>> | null>;
@@ -24,7 +25,7 @@ export interface FmsAPI {
24
25
  }
25
26
  export interface LogAPI {
26
27
  get(startUTC: Date, endUTC: Date, signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
27
- recent(lastSeenCounter: number, expectedEndUTCofLastSeen: Date | null | undefined): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
28
+ recent(lastSeenCounter: number, expectedEndUTCofLastSeen: Date | null | undefined, signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
28
29
  logForMaterial(materialID: number, signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
29
30
  logForMaterials(materialIDs: ReadonlyArray<number> | null | undefined): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
30
31
  logForSerial(serial: string, signal?: AbortSignal): Promise<ReadonlyArray<Readonly<api.ILogEntry>>>;
@@ -0,0 +1,27 @@
1
+ import { type Getter } from "jotai";
2
+ import type { ICurrentStatus } from "./api.js";
3
+ type CurrentStatusSession = {
4
+ readonly id: number;
5
+ readonly open: boolean;
6
+ readonly snapshot: {
7
+ readonly status: Readonly<ICurrentStatus>;
8
+ readonly source: "http" | "socket";
9
+ } | null;
10
+ };
11
+ export declare const currentStatusSessionAtom: import("jotai").PrimitiveAtom<CurrentStatusSession> & {
12
+ init: CurrentStatusSession;
13
+ };
14
+ export declare const currentStatusIsLiveRW: import("jotai").PrimitiveAtom<boolean> & {
15
+ init: boolean;
16
+ };
17
+ export declare const errorLoadingStatusRW: import("jotai").PrimitiveAtom<string | null> & {
18
+ init: string | null;
19
+ };
20
+ export declare function isCurrentSession(get: Getter, session: number): boolean;
21
+ export declare const onLoadCurrentSt: import("jotai").WritableAtom<null, [status: Readonly<ICurrentStatus>], void> & {
22
+ init: null;
23
+ };
24
+ export declare const acceptCurrentStatusSnapshot: import("jotai").WritableAtom<null, [session: number, status: Readonly<ICurrentStatus>, source: "http" | "socket"], boolean> & {
25
+ init: null;
26
+ };
27
+ export {};
@@ -0,0 +1,65 @@
1
+ /* Copyright (c) 2021, John Lenz
2
+
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ * Redistributions of source code must retain the above copyright
9
+ notice, this list of conditions and the following disclaimer.
10
+
11
+ * Redistributions in binary form must reproduce the above
12
+ copyright notice, this list of conditions and the following
13
+ disclaimer in the documentation and/or other materials provided
14
+ with the distribution.
15
+
16
+ * Neither the name of John Lenz, Black Maple Software, SeedTactics,
17
+ nor the names of other contributors may be used to endorse or
18
+ promote products derived from this software without specific
19
+ prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
+ */
33
+ import { atom } from "jotai";
34
+ import { setCurrentStatus } from "../cell-status/current-status.js";
35
+ import { replaceCustomState } from "../cell-status/custom-state.js";
36
+ import { setNamesFromCurrentStatus } from "../cell-status/names.js";
37
+ export const currentStatusSessionAtom = atom({
38
+ id: 0,
39
+ open: false,
40
+ snapshot: null,
41
+ });
42
+ export const currentStatusIsLiveRW = atom(false);
43
+ export const errorLoadingStatusRW = atom(null);
44
+ export function isCurrentSession(get, session) {
45
+ return get(currentStatusSessionAtom).id === session;
46
+ }
47
+ // Raw replacement also serves offline fixtures and local rollbacks. Live server snapshots must
48
+ // use acceptCurrentStatusSnapshot so the display and its comparison revision move together.
49
+ export const onLoadCurrentSt = atom(null, (_, set, status) => {
50
+ set(setCurrentStatus, status);
51
+ set(replaceCustomState, status.customState ?? null);
52
+ set(setNamesFromCurrentStatus, status);
53
+ });
54
+ export const acceptCurrentStatusSnapshot = atom(null, (get, set, session, status, source) => {
55
+ const current = get(currentStatusSessionAtom);
56
+ const installed = current.snapshot?.status;
57
+ if (current.id !== session || (installed && status.revision <= installed.revision))
58
+ return false;
59
+ set(onLoadCurrentSt, status);
60
+ set(currentStatusSessionAtom, { ...current, snapshot: { status, source } });
61
+ if (current.open)
62
+ set(currentStatusIsLiveRW, true);
63
+ set(errorLoadingStatusRW, null);
64
+ return true;
65
+ });
@@ -1,4 +1,8 @@
1
1
  import { Atom } from "jotai";
2
2
  export declare const websocketReconnecting: Atom<boolean>;
3
+ export declare const currentStatusIsLive: Atom<boolean>;
3
4
  export declare const errorLoadingLast30: Atom<string | null>;
5
+ export declare const refreshCurrentStatus: import("jotai").WritableAtom<null, [signal?: AbortSignal | undefined], Promise<boolean>> & {
6
+ init: null;
7
+ };
4
8
  export declare function WebsocketConnection(): null;
@@ -30,39 +30,142 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
30
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
31
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
32
  */
33
+ import { acceptCurrentStatusSnapshot, currentStatusSessionAtom, currentStatusIsLiveRW, errorLoadingStatusRW, isCurrentSession, } from "./current-status-session.js";
33
34
  import { ServerEvent } from "./api.js";
35
+ import { apiErrorMessage } from "./api-errors.js";
34
36
  import { JobsBackend, LogBackend } from "./backend.js";
35
37
  import { fmsInformation } from "./server-settings.js";
36
- import { useCallback, useEffect, useRef } from "react";
37
- import { lastEventCounter, onLoadCurrentSt, onLoadLast30Jobs, onLoadLast30Log, onServerEvent, } from "../cell-status/loading.js";
38
+ import { useEffect, useRef } from "react";
39
+ import { lastEventCounter, onLoadLast30Jobs, onLoadLast30Log, onLiveServerEvent, onHistoricalServerEvent, } from "../cell-status/loading.js";
38
40
  import { addDays } from "date-fns";
39
41
  import { last30SchIds } from "../cell-status/scheduled-jobs.js";
42
+ import { currentStatus } from "../cell-status/current-status.js";
43
+ import { HashSet, OrderedMap } from "@seedtactics/immutable-collections";
40
44
  import { atom, useAtomValue, useSetAtom } from "jotai";
41
45
  const websocketReconnectingAtom = atom(false);
42
46
  export const websocketReconnecting = websocketReconnectingAtom;
47
+ // True while the websocket is open and this connection has loaded or received a current status, so
48
+ // the retained current status reflects the server. Loading the historical jobs and log does not
49
+ // affect it.
50
+ export const currentStatusIsLive = currentStatusIsLiveRW;
51
+ // Only historical effects wait for HTTP catch-up. A fresh session discards its predecessor's
52
+ // unapplied buffer and reloads from lastEventCounter, which has not advanced past that history.
53
+ const bufferedLogAtom = atom(null);
54
+ // HTTP can include entries whose socket messages arrive after the response. Suppress those exact
55
+ // identities, never all counters below a maximum: live publication is not guaranteed to be ordered.
56
+ const loadedLogCountersAtom = atom(HashSet.empty());
43
57
  const errorLoadingLast30RW = atom(null);
44
- export const errorLoadingLast30 = errorLoadingLast30RW;
45
- function loadInitial(set) {
46
- const now = new Date();
47
- const thirtyDaysAgo = addDays(now, -30);
48
- const curStProm = JobsBackend.currentStatus().then((st) => set(onLoadCurrentSt, st));
49
- const jobsProm = JobsBackend.recent(thirtyDaysAgo, []).then((j) => set(onLoadLast30Jobs, j));
50
- const logProm = LogBackend.get(thirtyDaysAgo, now).then((log) => set(onLoadLast30Log, log));
51
- Promise.all([curStProm, jobsProm, logProm])
52
- .catch((e) => set(errorLoadingLast30RW, e.message ?? "Error"))
53
- .finally(() => set(websocketReconnectingAtom, false));
58
+ const errorLoadingLogRW = atom(null);
59
+ export const errorLoadingLast30 = atom((get) => get(errorLoadingStatusRW) ?? get(errorLoadingLast30RW) ?? get(errorLoadingLogRW));
60
+ async function loadCurrentStatus(get, set, session, signal) {
61
+ while (isCurrentSession(get, session)) {
62
+ const before = get(currentStatus);
63
+ const snapshot = get(currentStatusSessionAtom).snapshot;
64
+ let st;
65
+ try {
66
+ signal?.throwIfAborted();
67
+ st = await JobsBackend.currentStatus(signal);
68
+ signal?.throwIfAborted();
69
+ }
70
+ catch (error) {
71
+ const current = get(currentStatusSessionAtom);
72
+ if (current.id !== session)
73
+ return false;
74
+ if (!signal?.aborted &&
75
+ current.snapshot !== snapshot &&
76
+ current.snapshot?.source === "socket")
77
+ return true;
78
+ throw error;
79
+ }
80
+ const current = get(currentStatusSessionAtom);
81
+ if (current.id !== session)
82
+ return false;
83
+ const installed = current.snapshot?.status;
84
+ if (installed && st.revision <= installed.revision)
85
+ return true;
86
+ // A higher server revision can replace an intervening complete snapshot, but a log edit or
87
+ // optimistic local edit still needs a fresh read rather than being overwritten.
88
+ if (get(currentStatus) !== before && get(currentStatus) !== installed)
89
+ continue;
90
+ set(acceptCurrentStatusSnapshot, session, st, "http");
91
+ return true;
92
+ }
93
+ return false;
54
94
  }
55
- function loadMissed(lastCntr, schIds, set) {
95
+ // Every caller starts its own read, after its action has settled. Session ownership stays here.
96
+ export const refreshCurrentStatus = atom(null, (get, set, signal) => loadCurrentStatus(get, set, get(currentStatusSessionAtom).id, signal));
97
+ async function loadBootstrapStatus(get, set, session, retryDelay = 1000) {
98
+ try {
99
+ await loadCurrentStatus(get, set, session, AbortSignal.timeout(10000));
100
+ }
101
+ catch (error) {
102
+ if (!isCurrentSession(get, session) || get(currentStatusIsLiveRW))
103
+ return;
104
+ set(errorLoadingStatusRW, apiErrorMessage(error, "Error loading current status"));
105
+ setTimeout(() => {
106
+ if (isCurrentSession(get, session) && !get(currentStatusIsLiveRW)) {
107
+ void loadBootstrapStatus(get, set, session, Math.min(retryDelay * 2, 30000));
108
+ }
109
+ }, retryDelay);
110
+ }
111
+ }
112
+ function loadHistory(get, set, session, from, retryDelay = 1000) {
56
113
  const now = new Date();
57
- const curStProm = JobsBackend.currentStatus().then((st) => set(onLoadCurrentSt, st));
58
- const jobsProm = JobsBackend.recent(addDays(now, -30), schIds ? Array.from(schIds) : []).then((j) => set(onLoadLast30Jobs, j));
59
- const logProm = LogBackend.recent(lastCntr, undefined).then((log) => set(onLoadLast30Log, log));
60
- Promise.all([curStProm, jobsProm, logProm])
61
- .catch((e) => set(errorLoadingLast30RW, e.message ?? "Error"))
62
- .finally(() => set(websocketReconnectingAtom, false));
114
+ // Initial history can be much larger than status. Bound both headers and body reads, then
115
+ // retry from the same applied position while retaining buffered socket events.
116
+ const signal = AbortSignal.timeout(120000);
117
+ const request = from === null
118
+ ? LogBackend.get(addDays(now, -30), now, signal)
119
+ : LogBackend.recent(from, undefined, signal);
120
+ return request.then((log) => {
121
+ if (!isCurrentSession(get, session))
122
+ return;
123
+ const buffered = get(bufferedLogAtom) ?? OrderedMap.empty();
124
+ const merged = log.reduce((entries, entry) => entries.set(entry.counter, entry), buffered);
125
+ set(onLoadLast30Log, merged.valuesToAscLazySeq().toRArray());
126
+ set(loadedLogCountersAtom, HashSet.from(merged.keys()));
127
+ set(bufferedLogAtom, null);
128
+ set(errorLoadingLogRW, null);
129
+ }, (e) => {
130
+ if (!isCurrentSession(get, session))
131
+ return;
132
+ set(errorLoadingLogRW, signal.aborted
133
+ ? "Loading log history timed out."
134
+ : apiErrorMessage(e, "Error loading log history"));
135
+ // Keep buffering and retry from the same applied position without interrupting live status.
136
+ setTimeout(() => {
137
+ if (isCurrentSession(get, session)) {
138
+ void loadHistory(get, set, session, from, Math.min(retryDelay * 2, 30000));
139
+ }
140
+ }, retryDelay);
141
+ });
142
+ }
143
+ function loadConnection(get, set, session) {
144
+ const from = get(lastEventCounter);
145
+ const schIds = get(last30SchIds);
146
+ const curStProm = loadBootstrapStatus(get, set, session);
147
+ const jobsProm = JobsBackend.recent(addDays(new Date(), -30), from !== null && schIds ? Array.from(schIds) : []).then((j) => {
148
+ if (isCurrentSession(get, session))
149
+ set(onLoadLast30Jobs, j);
150
+ });
151
+ const logProm = loadHistory(get, set, session, from);
152
+ finishLoading([curStProm, jobsProm, logProm], get, set, session);
153
+ }
154
+ function finishLoading(loads, get, set, session) {
155
+ Promise.all(loads)
156
+ .catch((e) => {
157
+ if (isCurrentSession(get, session)) {
158
+ set(errorLoadingLast30RW, apiErrorMessage(e, "Error"));
159
+ }
160
+ })
161
+ .finally(() => {
162
+ if (isCurrentSession(get, session))
163
+ set(websocketReconnectingAtom, false);
164
+ });
63
165
  }
64
166
  class ReconnectingWebsocket {
65
167
  constructor(url) {
168
+ this.session = null;
66
169
  this.userCalledClose = false;
67
170
  this.reconnectAttempts = 0;
68
171
  this.url = url;
@@ -71,6 +174,12 @@ class ReconnectingWebsocket {
71
174
  close() {
72
175
  this.userCalledClose = true;
73
176
  this.ws?.close();
177
+ this.endSession(false);
178
+ }
179
+ endSession(reconnecting) {
180
+ const session = this.session;
181
+ this.session = null;
182
+ this.handleClose?.(session, reconnecting);
74
183
  }
75
184
  connect() {
76
185
  if (this.userCalledClose)
@@ -83,7 +192,7 @@ class ReconnectingWebsocket {
83
192
  localWs.addEventListener("open", () => {
84
193
  clearTimeout(connectTimeout);
85
194
  this.reconnectAttempts = 0;
86
- this.handleOpen?.();
195
+ this.session = this.handleOpen?.() ?? null;
87
196
  });
88
197
  localWs.addEventListener("close", () => {
89
198
  clearTimeout(connectTimeout);
@@ -91,7 +200,7 @@ class ReconnectingWebsocket {
91
200
  if (this.userCalledClose) {
92
201
  return;
93
202
  }
94
- this.handleReconnecting?.();
203
+ this.endSession(true);
95
204
  const delay = Math.min(1000 * Math.pow(1.5, this.reconnectAttempts), 30000);
96
205
  setTimeout(() => {
97
206
  this.reconnectAttempts++;
@@ -99,7 +208,7 @@ class ReconnectingWebsocket {
99
208
  }, delay);
100
209
  });
101
210
  localWs.addEventListener("message", (evt) => {
102
- this.handleMessage?.(evt);
211
+ this.handleMessage?.(evt, this.session);
103
212
  });
104
213
  // Browsers expose websocket failures as opaque events with no useful detail.
105
214
  // Reconnect handling is driven by close/open, so avoid polluting stderr by
@@ -107,25 +216,55 @@ class ReconnectingWebsocket {
107
216
  }
108
217
  }
109
218
  const onOpenAtom = atom(null, (get, set) => {
110
- const lastSeenCntr = get(lastEventCounter);
111
- const schIds = get(last30SchIds);
219
+ const session = get(currentStatusSessionAtom).id + 1;
220
+ set(currentStatusSessionAtom, { id: session, open: true, snapshot: null });
112
221
  set(websocketReconnectingAtom, true);
222
+ set(currentStatusIsLiveRW, false);
113
223
  set(errorLoadingLast30RW, null);
114
- if (lastSeenCntr !== null && lastSeenCntr !== undefined) {
115
- loadMissed(lastSeenCntr, schIds, set);
116
- }
117
- else {
118
- loadInitial(set);
119
- }
224
+ set(errorLoadingLogRW, null);
225
+ set(errorLoadingStatusRW, null);
226
+ set(bufferedLogAtom, OrderedMap.empty());
227
+ loadConnection(get, set, session);
228
+ return session;
229
+ });
230
+ // Every close, including disposal, ends the socket's own session; only an unexpected close
231
+ // reconnects. A connection cannot end a newer connection's session.
232
+ const onCloseAtom = atom(null, (get, set, session, reconnecting) => {
233
+ if (reconnecting)
234
+ set(websocketReconnectingAtom, true);
235
+ if (session === null || !isCurrentSession(get, session))
236
+ return;
237
+ set(currentStatusSessionAtom, { id: session + 1, open: false, snapshot: null });
238
+ set(currentStatusIsLiveRW, false);
239
+ set(bufferedLogAtom, null);
120
240
  });
121
- const onMessageAtom = atom(null, (_, set, evt) => {
122
- const serverEvt = ServerEvent.fromJS(JSON.parse(evt.data));
123
- set(onServerEvent, { evt: serverEvt, now: new Date(), expire: true });
241
+ const onMessageAtom = atom(null, (get, set, evt, session) => {
242
+ if (session === null || !isCurrentSession(get, session))
243
+ return;
244
+ const received = ServerEvent.fromJS(JSON.parse(evt.data));
245
+ const status = received.newCurrentStatus;
246
+ const accepted = status && set(acceptCurrentStatusSnapshot, session, status, "socket");
247
+ const serverEvt = status && !accepted
248
+ ? new ServerEvent({ logEntry: received.logEntry, newJobs: received.newJobs })
249
+ : received;
250
+ const eventAndTime = { evt: serverEvt, now: new Date(), expire: true };
251
+ // Complete snapshots were installed above; standalone log edits still apply immediately.
252
+ if (!serverEvt.newCurrentStatus)
253
+ set(onLiveServerEvent, eventAndTime);
254
+ const log = serverEvt.logEntry;
255
+ const buffered = get(bufferedLogAtom);
256
+ if (!log || !get(loadedLogCountersAtom).has(log.counter)) {
257
+ if (log && buffered !== null) {
258
+ set(bufferedLogAtom, buffered.set(log.counter, log));
259
+ }
260
+ else {
261
+ set(onHistoricalServerEvent, eventAndTime);
262
+ }
263
+ }
124
264
  });
125
265
  export function WebsocketConnection() {
126
266
  const onOpen = useSetAtom(onOpenAtom);
127
- const setReconnecting = useSetAtom(websocketReconnectingAtom);
128
- const onReconnecting = useCallback(() => setReconnecting(true), [setReconnecting]);
267
+ const onClose = useSetAtom(onCloseAtom);
129
268
  const onMessage = useSetAtom(onMessageAtom);
130
269
  const fmsInfoLoadable = useAtomValue(fmsInformation);
131
270
  const websocketRef = useRef(null);
@@ -151,7 +290,7 @@ export function WebsocketConnection() {
151
290
  }
152
291
  const websocket = new ReconnectingWebsocket(uri);
153
292
  websocket.handleOpen = onOpen;
154
- websocket.handleReconnecting = onReconnecting;
293
+ websocket.handleClose = onClose;
155
294
  websocket.handleMessage = onMessage;
156
295
  websocketRef.current = websocket;
157
296
  return () => {
@@ -160,6 +299,6 @@ export function WebsocketConnection() {
160
299
  websocketRef.current = null;
161
300
  }
162
301
  };
163
- }, [fmsInfoLoadable, onMessage, onOpen, onReconnecting]);
302
+ }, [fmsInfoLoadable, onMessage, onOpen, onClose]);
164
303
  return null;
165
304
  }