@geode/opengeodeweb-front 12.1.0 → 12.2.0-rc.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 (57) hide show
  1. package/.build/server/utils/microservices_process.js +1 -1
  2. package/.build/tests/browser/helpers/crs.js +136 -0
  3. package/.build/tests/browser/helpers/crs_flows.js +60 -0
  4. package/.build/tests/browser/helpers/crs_shortlist.js +13 -0
  5. package/.build/tests/browser/helpers/crs_test_data.js +40 -0
  6. package/.build/tests/browser/suites/crs.js +142 -0
  7. package/.build/tests/browser/suites/crs_harmonize.js +63 -0
  8. package/.build/tests/browser/suites/crs_shortlist.js +31 -0
  9. package/.build/tests/browser/suites/index.js +6 -0
  10. package/app/app.config.ts +4 -0
  11. package/app/components/CrsAlign.vue +207 -0
  12. package/app/components/CrsDialog.vue +400 -0
  13. package/app/components/CrsDialogHost.vue +66 -0
  14. package/app/components/CrsSelector.vue +100 -3
  15. package/app/components/PickButton.vue +43 -0
  16. package/app/components/ProjectCrsDialog.vue +109 -0
  17. package/app/components/ToolPanel.vue +5 -2
  18. package/app/components/Viewer/CrsOverlays.vue +29 -0
  19. package/app/components/Viewer/Ui.vue +3 -2
  20. package/app/composables/crs.ts +197 -0
  21. package/app/composables/crs_align.ts +206 -0
  22. package/app/composables/crs_assign.ts +102 -0
  23. package/app/composables/crs_link.ts +22 -0
  24. package/app/composables/crs_shortlist.ts +63 -0
  25. package/app/composables/project_crs.ts +197 -0
  26. package/app/composables/user_setting.ts +140 -0
  27. package/app/plugins/activity_connections.client.ts +9 -0
  28. package/app/stores/activity.ts +130 -0
  29. package/app/stores/back.ts +7 -2
  30. package/app/stores/basemap.ts +19 -2
  31. package/app/stores/cloud.ts +1 -1
  32. package/app/stores/crs.ts +11 -106
  33. package/app/stores/crs_helpers/geographic_list.ts +44 -0
  34. package/app/stores/crs_helpers/project_crs.ts +60 -0
  35. package/app/stores/crs_helpers/requests.ts +60 -0
  36. package/app/utils/activity_connections.ts +36 -0
  37. package/app/utils/activity_params.ts +40 -0
  38. package/app/utils/crs.ts +17 -1
  39. package/app/utils/import_item.ts +87 -0
  40. package/app/utils/import_workflow.ts +36 -94
  41. package/app/utils/log.ts +4 -1
  42. package/app/utils/reload_object.ts +26 -0
  43. package/internal/utils/api_fetch.ts +13 -2
  44. package/internal/utils/track_request.ts +74 -0
  45. package/internal/utils/upload_file.ts +73 -39
  46. package/internal/utils/viewer_call.ts +49 -39
  47. package/package.json +5 -5
  48. package/server/utils/microservices_process.ts +4 -1
  49. package/tests/browser/data/test_lambert93_no_crs.og_pts3d +0 -0
  50. package/tests/browser/data/test_utm31n.og_pts3d +0 -0
  51. package/tests/browser/helpers/crs.ts +250 -0
  52. package/tests/browser/helpers/crs_flows.ts +115 -0
  53. package/tests/browser/helpers/crs_shortlist.ts +27 -0
  54. package/tests/browser/helpers/crs_test_data.ts +34 -0
  55. package/tests/browser/suites/crs.ts +228 -0
  56. package/tests/browser/suites/crs_harmonize.ts +96 -0
  57. package/tests/browser/suites/crs_shortlist.ts +37 -0
@@ -0,0 +1,36 @@
1
+ import { Status } from "@ogw_front/utils/status";
2
+ import { useActivityStore } from "@ogw_front/stores/activity";
3
+ import { useInfraStore } from "@ogw_front/stores/infra";
4
+
5
+ // Writes each microservice connection and disconnection to the activity panel
6
+ function watchMicroserviceConnections(): void {
7
+ const infraStore = useInfraStore();
8
+ const activityStore = useActivityStore();
9
+ const known = new Map<string, string | undefined>();
10
+
11
+ watch(
12
+ () => infraStore.microservices.map((store) => [store.$id, store.status] as const),
13
+ (statuses) => {
14
+ for (const [source, status] of statuses) {
15
+ const previous = known.get(source);
16
+ known.set(source, status);
17
+ if (status === previous) {
18
+ continue;
19
+ }
20
+ if (status === Status.CONNECTED) {
21
+ activityStore.log({ source, kind: "connection", route: "Connected", status: "info" });
22
+ } else if (previous === Status.CONNECTED) {
23
+ activityStore.log({
24
+ source,
25
+ kind: "connection",
26
+ route: "Connection lost",
27
+ status: "error",
28
+ });
29
+ }
30
+ }
31
+ },
32
+ { immediate: true },
33
+ );
34
+ }
35
+
36
+ export { watchMicroserviceConnections };
@@ -0,0 +1,40 @@
1
+ // Request params shown in the activity panel: a short JSON, never the whole payload (id lists, styles, files...)
2
+ const MAX_ARRAY_ITEMS = 10;
3
+ const MAX_STRING_LENGTH = 120;
4
+ const MAX_SUMMARY_LENGTH = 400;
5
+ const ELLIPSIS = "…";
6
+
7
+ function truncate(text: string, maxLength: number): string {
8
+ return text.length > maxLength ? `${text.slice(0, maxLength)}${ELLIPSIS}` : text;
9
+ }
10
+
11
+ function shorten(_key: string, value: unknown): unknown {
12
+ if (typeof value === "string") {
13
+ return truncate(value, MAX_STRING_LENGTH);
14
+ }
15
+ if (Array.isArray(value) && value.length > MAX_ARRAY_ITEMS) {
16
+ const items: unknown[] = value.slice(0, MAX_ARRAY_ITEMS);
17
+ return [...items, `${ELLIPSIS} +${value.length - MAX_ARRAY_ITEMS}`];
18
+ }
19
+ if (typeof Blob !== "undefined" && value instanceof Blob) {
20
+ return `<${value.size} bytes>`;
21
+ }
22
+ return value;
23
+ }
24
+
25
+ function summarizeParams(params: unknown): string | undefined {
26
+ if (params === undefined || params === null) {
27
+ return undefined;
28
+ }
29
+ if (typeof params === "object" && Object.keys(params).length === 0) {
30
+ return undefined;
31
+ }
32
+ try {
33
+ const json = JSON.stringify(params, shorten);
34
+ return truncate(json, MAX_SUMMARY_LENGTH);
35
+ } catch {
36
+ return "<unserializable params>";
37
+ }
38
+ }
39
+
40
+ export { summarizeParams };
package/app/utils/crs.ts CHANGED
@@ -1,6 +1,21 @@
1
1
  import type { CrsItem, NewDataItem } from "@ogw_front/stores/data";
2
2
  import type { CRS } from "@geode/opengeodeweb-back/schema_types";
3
3
  import type { LegacyDataId } from "@ogw_front/utils/legacy_data_id";
4
+ import { z } from "zod";
5
+
6
+ // Only what a CRS selector shows: the back may add other fields
7
+ interface CrsEntry {
8
+ authority: string;
9
+ code: string;
10
+ name: string;
11
+ }
12
+
13
+ // A stored CRS entry (favorites, history): unknown fields are dropped on read
14
+ const crsEntrySchema = z.object({
15
+ authority: z.string(),
16
+ code: z.string(),
17
+ name: z.string(),
18
+ });
4
19
 
5
20
  function formatCrs(crs: CRS | undefined): string {
6
21
  return crs ? `${crs.authority}:${crs.code} — ${crs.name}` : "None";
@@ -38,4 +53,5 @@ function oldestCrs(
38
53
  ?.crs;
39
54
  }
40
55
 
41
- export { formatCrs, formatCrsCode, oldestCrs, sameCrs, sameCrsState };
56
+ export type { CrsEntry };
57
+ export { crsEntrySchema, formatCrs, formatCrsCode, oldestCrs, sameCrs, sameCrsState };
@@ -0,0 +1,87 @@
1
+ // Local imports
2
+ import { type LegacyDataId, fromLegacyDataId } from "@ogw_front/utils/legacy_data_id";
3
+ import { type NewDataItem, useDataStore } from "@ogw_front/stores/data";
4
+ import { useDataStyleStore } from "@ogw_front/stores/data_style";
5
+ import { useFeedbackStore } from "@ogw_front/stores/feedback";
6
+ import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer";
7
+ import { useTreeviewStore } from "@ogw_front/stores/treeview";
8
+
9
+ // Steps that need the data stored first, and run only for the data the viewer shows
10
+ async function registerWhenViewable(item: NewDataItem, added: Promise<unknown>): Promise<unknown> {
11
+ const dataStore = useDataStore();
12
+ await added;
13
+ if (!(await dataStore.isItemViewable(item))) {
14
+ return undefined;
15
+ }
16
+ return dataStore.registerObject(item.data_id, item.name ?? item.data_id);
17
+ }
18
+
19
+ async function addToViewerWhenViewable(
20
+ item: NewDataItem,
21
+ added: Promise<unknown>,
22
+ ): Promise<unknown> {
23
+ const dataStore = useDataStore();
24
+ await added;
25
+ if (!(await dataStore.isItemViewable(item))) {
26
+ return undefined;
27
+ }
28
+ return useHybridViewerStore().addItem(item.data_id);
29
+ }
30
+
31
+ async function applyStyleWhenReady(item: NewDataItem, ready: Promise<unknown>): Promise<unknown> {
32
+ await ready;
33
+ if (!(await useDataStore().isItemViewable(item))) {
34
+ return undefined;
35
+ }
36
+ return useDataStyleStore().applyDefaultStyle(item.data_id);
37
+ }
38
+
39
+ // NewDataItem has mutable array fields (mesh_components, collection_components), so it can't
40
+ // Satisfy prefer-readonly-parameter-types deeply; left unfixed (same pattern as app/plugins/auto_store_register.ts).
41
+ async function importDataItem(item: NewDataItem): Promise<string> {
42
+ const dataStore = useDataStore();
43
+ const dataStyleStore = useDataStyleStore();
44
+ const treeviewStore = useTreeviewStore();
45
+ if (item.nb_vertices === 0) {
46
+ const feedbackStore = useFeedbackStore();
47
+ feedbackStore.add_warning(`"${item.geode_object_type}" with name "${item.name}" is empty`);
48
+ }
49
+ const addDataTask = dataStore.addItem(item);
50
+ const registerTask = registerWhenViewable(item, addDataTask);
51
+ let addDataComponentsTask: Promise<unknown> = Promise.resolve(undefined);
52
+ let addDataRelationsTask: Promise<unknown> = Promise.resolve(undefined);
53
+ if (item.viewer_object_type === "model") {
54
+ addDataComponentsTask = dataStore.addComponents(item);
55
+ addDataRelationsTask = dataStore.addComponentRelations(item);
56
+ }
57
+ treeviewStore.addItem(
58
+ item.geode_object_type,
59
+ item.name ?? item.data_id,
60
+ item.data_id,
61
+ item.geode_id,
62
+ item.viewer_object_type,
63
+ );
64
+ const addDataStyleTask = dataStyleStore.addDataStyle(item.data_id, item.geode_object_type);
65
+ const addViewerTask = addToViewerWhenViewable(item, addDataTask);
66
+ const applyStyleTask = applyStyleWhenReady(
67
+ item,
68
+ Promise.all([registerTask, addDataComponentsTask, addDataStyleTask]),
69
+ );
70
+ await Promise.all([
71
+ registerTask,
72
+ addDataTask,
73
+ addDataComponentsTask,
74
+ addDataRelationsTask,
75
+ addViewerTask,
76
+ applyStyleTask,
77
+ ]);
78
+ return item.data_id;
79
+ }
80
+ // Every item comes through here: from the back-end, which still names its data id `id`, or from a project
81
+ async function importItem(imported: LegacyDataId<NewDataItem> | NewDataItem): Promise<string> {
82
+ const item = fromLegacyDataId(imported);
83
+ const dataId = await useTreeviewStore().untilLoaded(item.data_id, importDataItem(item));
84
+ return dataId;
85
+ }
86
+
87
+ export { importItem };
@@ -1,86 +1,26 @@
1
- // oxlint-disable promise/prefer-await-to-then
2
1
  // Third party imports
3
2
  import back_schemas from "@geode/opengeodeweb-back/opengeodeweb_back_typed_schemas.js";
4
3
  import { consola } from "consola";
5
4
 
6
5
  // Local imports
7
- import { type LegacyDataId, fromLegacyDataId } from "@ogw_front/utils/legacy_data_id";
8
6
  import { type NewDataItem, useDataStore } from "@ogw_front/stores/data";
7
+ import type { CRS } from "@geode/opengeodeweb-back/schema_types";
9
8
  import type { DataId } from "@geode/opengeodeweb-microservice/schema_types";
10
9
  import type { GeodeObjectType } from "@geode/opengeodeweb-microservice/data_types";
11
10
  import type { GeodeObjectTyped } from "@ogw_front/types/identifiers";
11
+ import type { LegacyDataId } from "@ogw_front/utils/legacy_data_id";
12
+ import { importItem } from "@ogw_front/utils/import_item";
13
+ import { reloadObject } from "@ogw_front/utils/reload_object";
12
14
  import { useBackStore } from "@ogw_front/stores/back";
13
- import { useDataStyleStore } from "@ogw_front/stores/data_style";
14
- import { useFeedbackStore } from "@ogw_front/stores/feedback";
15
+ import { useCrsStore } from "@ogw_front/stores/crs";
15
16
  import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer";
17
+ import { useProjectCrs } from "@ogw_front/composables/project_crs";
16
18
  import { useTreeviewStore } from "@ogw_front/stores/treeview";
17
19
 
18
20
  interface FileToImport extends Readonly<GeodeObjectTyped> {
19
21
  readonly filename: string;
20
22
  }
21
23
 
22
- // NewDataItem has mutable array fields (mesh_components, collection_components), so it can't
23
- // Satisfy prefer-readonly-parameter-types deeply; left unfixed (same pattern as app/plugins/auto_store_register.ts).
24
- async function importDataItem(item: NewDataItem): Promise<string> {
25
- const dataStore = useDataStore();
26
- const dataStyleStore = useDataStyleStore();
27
- const hybridViewerStore = useHybridViewerStore();
28
- const treeviewStore = useTreeviewStore();
29
- if (item.nb_vertices === 0) {
30
- const feedbackStore = useFeedbackStore();
31
- feedbackStore.add_warning(`"${item.geode_object_type}" with name "${item.name}" is empty`);
32
- }
33
- const addDataTask = dataStore.addItem(item);
34
- const registerTask = addDataTask.then(async () => {
35
- if (!(await dataStore.isItemViewable(item))) {
36
- return undefined;
37
- }
38
- return dataStore.registerObject(item.data_id, item.name ?? item.data_id);
39
- });
40
- let addDataComponentsTask: Promise<string | undefined> = Promise.resolve(undefined);
41
- let addDataRelationsTask: Promise<string | undefined> = Promise.resolve(undefined);
42
- if (item.viewer_object_type === "model") {
43
- addDataComponentsTask = dataStore.addComponents(item);
44
- addDataRelationsTask = dataStore.addComponentRelations(item);
45
- }
46
- treeviewStore.addItem(
47
- item.geode_object_type,
48
- item.name ?? item.data_id,
49
- item.data_id,
50
- item.geode_id,
51
- item.viewer_object_type,
52
- );
53
- const addDataStyleTask = dataStyleStore.addDataStyle(item.data_id, item.geode_object_type);
54
- const addViewerTask = addDataTask.then(async () => {
55
- if (!(await dataStore.isItemViewable(item))) {
56
- return undefined;
57
- }
58
- return hybridViewerStore.addItem(item.data_id);
59
- });
60
- const applyStyleTask = Promise.all([registerTask, addDataComponentsTask, addDataStyleTask]).then(
61
- async () => {
62
- if (await dataStore.isItemViewable(item)) {
63
- return dataStyleStore.applyDefaultStyle(item.data_id);
64
- }
65
- return undefined;
66
- },
67
- );
68
- await Promise.all([
69
- registerTask,
70
- addDataTask,
71
- addDataComponentsTask,
72
- addDataRelationsTask,
73
- addViewerTask,
74
- applyStyleTask,
75
- ]);
76
- return item.data_id;
77
- }
78
- // Every item comes through here: from the back-end, which still names its data id `id`, or from a project
79
- async function importItem(imported: LegacyDataId<NewDataItem> | NewDataItem): Promise<string> {
80
- const item = fromLegacyDataId(imported);
81
- const dataId = await useTreeviewStore().untilLoaded(item.data_id, importDataItem(item));
82
- return dataId;
83
- }
84
24
  // A single file can hold several objects: every one of them is imported, ids are returned in the response order
85
25
  async function importFile(filename: string, geode_object_type: GeodeObjectType): Promise<string[]> {
86
26
  const backStore = useBackStore();
@@ -103,7 +43,7 @@ async function importFile(filename: string, geode_object_type: GeodeObjectType):
103
43
  return dataIds;
104
44
  }
105
45
 
106
- async function importWorkflow(files: readonly FileToImport[]): Promise<string[]> {
46
+ async function importFiles(files: readonly FileToImport[]): Promise<string[]> {
107
47
  const hybridViewerStore = useHybridViewerStore();
108
48
  // Files are imported concurrently and the viewer only frames the first actor to arrive, so the camera is reset once everything is loaded
109
49
  const wasSceneEmpty = Object.keys(hybridViewerStore.hybridDb).length === 0;
@@ -148,6 +88,32 @@ async function importWorkflow(files: readonly FileToImport[]): Promise<string[]>
148
88
  return results;
149
89
  }
150
90
 
91
+ // A harmonization failure is only logged: the import outcome does not depend on it
92
+ async function harmonize(ids: string[], projectCrs: CRS | undefined): Promise<void> {
93
+ try {
94
+ await useProjectCrs().harmonizeImportedCrs(ids, projectCrs);
95
+ } catch (error) {
96
+ consola.error("CRS harmonization failed:", error);
97
+ }
98
+ }
99
+
100
+ // When a file fails, the workflow throws without returning the imported ids: they are found by difference.
101
+ // The project CRS is read before the import, as the project follows the data as they land.
102
+ async function importWorkflow(files: readonly FileToImport[]): Promise<string[]> {
103
+ const { projectCrs } = useCrsStore();
104
+ const existingItems = await useDataStore().allItems();
105
+ const existingIds = new Set(existingItems.map((item) => item.data_id));
106
+ try {
107
+ const ids = await importFiles(files);
108
+ return ids;
109
+ } finally {
110
+ const items = await useDataStore().allItems();
111
+ const importedIds = items.map((item) => item.data_id).filter((id) => !existingIds.has(id));
112
+ // Conversions can be long: the caller is not kept waiting, the snackbars report the outcome
113
+ void harmonize(importedIds, projectCrs);
114
+ }
115
+ }
116
+
151
117
  // NewDataItem has mutable array fields (mesh_components, collection_components), so a readonly array of it can't satisfy prefer-readonly-parameter-types deeply; left unfixed (same pattern as app/plugins/auto_store_register.ts).
152
118
  async function importWorkflowFromSnapshot(
153
119
  items: readonly (LegacyDataId<NewDataItem> | NewDataItem)[],
@@ -182,25 +148,6 @@ async function importWorkflowFromSnapshot(
182
148
  return ids;
183
149
  }
184
150
 
185
- // Reloads the viewer object under the same id with its stored style, after the back rewrote its files.
186
- async function reloadObject(
187
- dataId: DataId,
188
- { rebuildActor = false }: { rebuildActor?: boolean } = {},
189
- ): Promise<void> {
190
- const dataStore = useDataStore();
191
- const dataStyleStore = useDataStyleStore();
192
- const hybridViewerStore = useHybridViewerStore();
193
- const item = await dataStore.item(dataId);
194
- await dataStore.deregisterObject(dataId);
195
- await dataStore.registerObject(dataId, item.name ?? dataId);
196
- // Only when the geometry moved: the local actor is rebuilt from the stored light viewable
197
- if (rebuildActor) {
198
- await hybridViewerStore.addItem(dataId);
199
- }
200
- await dataStyleStore.applyDefaultStyle(dataId);
201
- await hybridViewerStore.remoteRender();
202
- }
203
-
204
151
  // The time series only adds attributes to the model, so the viewer object is reloaded.
205
152
  async function applyTimeSeriesWorkflow(filename: string, dataId: DataId): Promise<string> {
206
153
  const backStore = useBackStore();
@@ -212,11 +159,6 @@ async function applyTimeSeriesWorkflow(filename: string, dataId: DataId): Promis
212
159
  return dataId;
213
160
  }
214
161
 
215
- export {
216
- importFile,
217
- importWorkflow,
218
- importWorkflowFromSnapshot,
219
- importItem,
220
- applyTimeSeriesWorkflow,
221
- reloadObject,
222
- };
162
+ export { importFile, importWorkflow, importWorkflowFromSnapshot, applyTimeSeriesWorkflow };
163
+ export { importItem } from "@ogw_front/utils/import_item";
164
+ export { reloadObject } from "@ogw_front/utils/reload_object";
package/app/utils/log.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { JsonRpcSchema } from "@ogw_shared/utils/types.js";
2
2
  import { consola } from "consola";
3
3
 
4
+ const MILLISECONDS_IN_SECOND = 1000;
5
+
4
6
  interface Loggable {
5
7
  $id: string;
6
8
  }
@@ -21,7 +23,8 @@ function endRequestLog(
21
23
  `[${microservice.$id}] Request completed:`,
22
24
  schema.$id,
23
25
  "in",
24
- requestEndingTime.getSeconds() - requestStartingTime.getSeconds(),
26
+ // Seconds of the whole duration, not the difference of the clock's seconds field (wrong across a minute)
27
+ (requestEndingTime.getTime() - requestStartingTime.getTime()) / MILLISECONDS_IN_SECOND,
25
28
  "s",
26
29
  );
27
30
  }
@@ -0,0 +1,26 @@
1
+ // Local imports
2
+ import type { DataId } from "@geode/opengeodeweb-microservice/schema_types";
3
+ import { useDataStore } from "@ogw_front/stores/data";
4
+ import { useDataStyleStore } from "@ogw_front/stores/data_style";
5
+ import { useHybridViewerStore } from "@ogw_front/stores/hybrid_viewer";
6
+
7
+ // Reloads the viewer object under the same id with its stored style, after the back rewrote its files.
8
+ async function reloadObject(
9
+ dataId: DataId,
10
+ { rebuildActor = false }: { rebuildActor?: boolean } = {},
11
+ ): Promise<void> {
12
+ const dataStore = useDataStore();
13
+ const dataStyleStore = useDataStyleStore();
14
+ const hybridViewerStore = useHybridViewerStore();
15
+ const item = await dataStore.item(dataId);
16
+ await dataStore.deregisterObject(dataId);
17
+ await dataStore.registerObject(dataId, item.name ?? dataId);
18
+ // Only when the geometry moved: the local actor is rebuilt from the stored light viewable
19
+ if (rebuildActor) {
20
+ await hybridViewerStore.addItem(dataId);
21
+ }
22
+ await dataStyleStore.applyDefaultStyle(dataId);
23
+ await hybridViewerStore.remoteRender();
24
+ }
25
+
26
+ export { reloadObject };
@@ -3,6 +3,7 @@ import { endRequestLog, startRequestLog } from "@ogw_front/utils/log";
3
3
  import { reportError, reportTimeout } from "./error_feedback.js";
4
4
  import { consola } from "consola";
5
5
  import { fetchSchema } from "@ogw_shared/utils/fetch_schema";
6
+ import { trackRequest } from "./track_request.js";
6
7
  import { useFeedbackStore } from "@ogw_front/stores/feedback";
7
8
 
8
9
  // The microservice-backed Pinia stores (back/app/...) all expose this shape; only the slice actually used here needs to be declared.
@@ -18,12 +19,14 @@ interface ApiFetchParams {
18
19
  schema: JsonRpcSchema & { methods: string[] };
19
20
  params?: object;
20
21
  headers?: Record<string, string>;
22
+ // False for the requests repeated in the background (pings): the activity panel only shows their failures
23
+ log_success?: boolean;
21
24
  }
22
25
 
23
26
  // oxlint-disable-next-line max-lines-per-function
24
27
  async function api_fetch(
25
28
  microservice: Microservice,
26
- { schema, params = {}, headers = {} }: ApiFetchParams,
29
+ { schema, params = {}, headers = {}, log_success = true }: ApiFetchParams,
27
30
  {
28
31
  request_error_function,
29
32
  response_function,
@@ -37,7 +40,14 @@ async function api_fetch(
37
40
  microservice.start_request();
38
41
 
39
42
  const requestStartingTime = startRequestLog(microservice, schema);
40
- const request = fetchSchema(
43
+ const followRequest = trackRequest({
44
+ source: microservice.$id,
45
+ kind: "http",
46
+ route: schema.$id,
47
+ params,
48
+ log_success,
49
+ });
50
+ const pending = fetchSchema(
41
51
  {
42
52
  schema,
43
53
  params,
@@ -77,6 +87,7 @@ async function api_fetch(
77
87
  },
78
88
  },
79
89
  );
90
+ const request = followRequest(pending);
80
91
  if (skip_feedback_error === true) {
81
92
  return request;
82
93
  }
@@ -0,0 +1,74 @@
1
+ import {
2
+ type ActivityEntryKind,
3
+ type ActivityOutcome,
4
+ useActivityStore,
5
+ } from "@ogw_front/stores/activity";
6
+ import { TimeoutError } from "p-timeout";
7
+ import { toErrorFeedback } from "./error_feedback.js";
8
+
9
+ interface TrackedRequest {
10
+ source: string;
11
+ kind: ActivityEntryKind;
12
+ route: string;
13
+ label?: string;
14
+ params?: unknown;
15
+ // False for the requests repeated in the background (pings): only their failures are logged
16
+ log_success?: boolean;
17
+ }
18
+
19
+ const GENERIC_ERROR_NAME = "Error";
20
+
21
+ // An ofetch FetchError keeps the microservice ErrorResponse in its response: read it as the snackbar does
22
+ function failedResponse(error: unknown): unknown {
23
+ if (typeof error === "object" && error !== null && "response" in error) {
24
+ const { response } = error;
25
+ if (typeof response === "object" && response !== null) {
26
+ return response;
27
+ }
28
+ }
29
+ return error;
30
+ }
31
+
32
+ function failureOf(error: unknown): ActivityOutcome {
33
+ const { name, description } = toErrorFeedback(failedResponse(error));
34
+ const message =
35
+ name === GENERIC_ERROR_NAME || description === name ? description : `${name}: ${description}`;
36
+ return { status: error instanceof TimeoutError ? "timeout" : "error", error: message };
37
+ }
38
+
39
+ type FollowRequest = <Result>(pending: Promise<Result>) => Promise<Result>;
40
+
41
+ // Opens the activity entry of a microservice request: call it before sending, then follow the request until it settles
42
+ function trackRequest({ log_success = true, ...request }: TrackedRequest): FollowRequest {
43
+ const activityStore = useActivityStore();
44
+ const started_at = Date.now();
45
+ let entryId: number | undefined = undefined;
46
+ if (log_success) {
47
+ entryId = activityStore.start_request(request);
48
+ }
49
+
50
+ return async <Result>(pending: Promise<Result>): Promise<Result> => {
51
+ try {
52
+ const result = await pending;
53
+ if (entryId !== undefined) {
54
+ activityStore.finish_request(entryId, { status: "success" });
55
+ }
56
+ return result;
57
+ } catch (error) {
58
+ const outcome = failureOf(error);
59
+ if (entryId === undefined) {
60
+ activityStore.log({
61
+ ...request,
62
+ ...outcome,
63
+ started_at,
64
+ duration_ms: Date.now() - started_at,
65
+ });
66
+ } else {
67
+ activityStore.finish_request(entryId, outcome);
68
+ }
69
+ throw error;
70
+ }
71
+ };
72
+ }
73
+
74
+ export { trackRequest };
@@ -4,6 +4,7 @@ import type { Microservice } from "./api_fetch.js";
4
4
  import { consola } from "consola";
5
5
  import { fetchRaw } from "@ogw_shared/utils/fetch_raw.js";
6
6
  import { reportError } from "./error_feedback.js";
7
+ import { trackRequest } from "./track_request.js";
7
8
  import { uploadPath } from "@ogw_front/utils/upload_path";
8
9
 
9
10
  interface UploadFileParams {
@@ -14,40 +15,44 @@ interface UploadFileParams {
14
15
  params?: Record<string, string>;
15
16
  }
16
17
 
17
- async function upload_file(
18
- microservice: Microservice,
19
- { schema, file, params = {} }: UploadFileParams,
20
- { request_error_function, response_function, response_error_function }: RequestHandlers = {},
21
- ): Promise<unknown> {
22
- consola.debug("[UPLOAD_FILE] Uploading file", { schema, file });
23
-
24
- if (!(file instanceof File)) {
25
- throw new TypeError("file must be an instance of File");
26
- }
27
-
28
- const route = schema.$id;
29
- const method = schema.methods.find((candidate) => candidate !== "OPTIONS");
30
- const totalChunks = Math.max(1, Math.ceil(file.size / CHUNK_SIZE_BYTES));
31
-
32
- function onRequestError(error: unknown): void {
33
- microservice.stop_request();
34
- reportError(route, error);
35
- if (request_error_function) {
36
- void request_error_function(error);
37
- }
38
- }
39
-
40
- function onResponseError(response: unknown): void {
41
- microservice.stop_request();
42
- reportError(route, response);
43
- if (response_error_function) {
44
- void response_error_function(response);
45
- }
46
- }
18
+ interface ChunkUpload {
19
+ microservice: Microservice;
20
+ route: string;
21
+ method: string | undefined;
22
+ file: File;
23
+ params: Record<string, string>;
24
+ totalChunks: number;
25
+ }
47
26
 
48
- microservice.start_request();
27
+ // A failed chunk stops the request and is reported before the caller's own handler runs
28
+ function chunkErrorHandlers(
29
+ microservice: Microservice,
30
+ route: string,
31
+ { request_error_function, response_error_function }: RequestHandlers,
32
+ ): RequestHandlers {
33
+ return {
34
+ request_error_function(error: unknown): void {
35
+ microservice.stop_request();
36
+ reportError(route, error);
37
+ if (request_error_function) {
38
+ void request_error_function(error);
39
+ }
40
+ },
41
+ response_error_function(response: unknown): void {
42
+ microservice.stop_request();
43
+ reportError(route, response);
44
+ if (response_error_function) {
45
+ void response_error_function(response);
46
+ }
47
+ },
48
+ };
49
+ }
49
50
 
50
- let result: unknown = undefined;
51
+ async function sendChunks(
52
+ { microservice, route, method, file, params, totalChunks }: ChunkUpload,
53
+ handlers: RequestHandlers,
54
+ ): Promise<unknown> {
55
+ let lastResponse: unknown = undefined;
51
56
  for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex += 1) {
52
57
  const start = chunkIndex * CHUNK_SIZE_BYTES;
53
58
  const chunk = file.slice(start, start + CHUNK_SIZE_BYTES);
@@ -59,23 +64,52 @@ async function upload_file(
59
64
  });
60
65
 
61
66
  // oxlint-disable-next-line no-await-in-loop -- chunks must be sent in order; the server appends each one to the file as it arrives.
62
- result = await fetchRaw(
67
+ lastResponse = await fetchRaw(
63
68
  {
64
69
  route: `${route}?${query.toString()}`,
65
70
  method,
66
71
  params: chunk,
67
72
  baseURL: microservice.base_url,
68
73
  },
69
- {
70
- request_error_function: onRequestError,
71
- response_error_function: onResponseError,
72
- },
74
+ handlers,
73
75
  );
74
76
  }
77
+ return lastResponse;
78
+ }
79
+
80
+ async function upload_file(
81
+ microservice: Microservice,
82
+ { schema, file, params = {} }: UploadFileParams,
83
+ handlers: RequestHandlers = {},
84
+ ): Promise<unknown> {
85
+ consola.debug("[UPLOAD_FILE] Uploading file", { schema, file });
86
+
87
+ if (!(file instanceof File)) {
88
+ throw new TypeError("file must be an instance of File");
89
+ }
90
+
91
+ const route = schema.$id;
92
+ const method = schema.methods.find((candidate) => candidate !== "OPTIONS");
93
+ const totalChunks = Math.max(1, Math.ceil(file.size / CHUNK_SIZE_BYTES));
94
+
95
+ microservice.start_request();
96
+ const followRequest = trackRequest({
97
+ source: microservice.$id,
98
+ kind: "upload",
99
+ route,
100
+ label: file.name,
101
+ params: { filename: uploadPath(file), size: file.size, chunks: totalChunks },
102
+ });
103
+ const result = await followRequest(
104
+ sendChunks(
105
+ { microservice, route, method, file, params, totalChunks },
106
+ chunkErrorHandlers(microservice, route, handlers),
107
+ ),
108
+ );
75
109
 
76
110
  microservice.stop_request();
77
- if (response_function) {
78
- response_function(result);
111
+ if (handlers.response_function) {
112
+ handlers.response_function(result);
79
113
  }
80
114
  return result;
81
115
  }