@oneuptime/common 14.0.6 → 14.0.7

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 (127) hide show
  1. package/Models/DatabaseModels/InventoryItem.ts +23 -12
  2. package/Server/Infrastructure/Postgres/SchemaMigrations/1795200000000-AddInventoryItemProjectEntityKeyIndex.ts +217 -0
  3. package/Server/Infrastructure/Postgres/SchemaMigrations/Index.ts +2 -0
  4. package/Server/Services/AlertService.ts +32 -36
  5. package/Server/Services/IncidentAlertService.ts +609 -2
  6. package/Server/Services/IncidentService.ts +134 -44
  7. package/Server/Services/InventoryItemService.ts +38 -0
  8. package/Server/Services/IoTDeviceCredentialService.ts +13 -4
  9. package/Server/Services/ScheduledMaintenanceService.ts +50 -46
  10. package/Server/Services/UserNotificationRuleService.ts +55 -53
  11. package/Server/Services/WorkspaceNotificationSummaryService.ts +38 -20
  12. package/Server/Utils/AffectedResources/LinkedAffectedResources.ts +576 -0
  13. package/Server/Utils/Alert/AlertStateChangeAuthorization.ts +129 -0
  14. package/Server/Utils/Inventory/InventoryOverviewAggregation.ts +111 -0
  15. package/Server/Utils/Response.ts +31 -0
  16. package/Server/Utils/Topology/TopologyConcurrencyLimiter.ts +229 -0
  17. package/Server/Utils/Topology/TopologyQueries.ts +1350 -0
  18. package/Server/Utils/Topology/TopologyRequest.ts +463 -0
  19. package/Server/Utils/Topology/TopologyResponseCache.ts +183 -0
  20. package/Server/Utils/Topology/TopologySql.ts +1024 -0
  21. package/Tests/App/Dashboard/AcknowledgeAlertsOnDeclare.test.ts +369 -0
  22. package/Tests/App/Dashboard/AffectedResourcesSlo.test.tsx +1 -1
  23. package/Tests/App/Dashboard/AffectedResourcesSummaryStep.test.tsx +510 -123
  24. package/Tests/App/Dashboard/AlertsTableAffectedResources.test.tsx +490 -0
  25. package/Tests/App/Dashboard/ChangeAlertStateDeclareIncident.test.tsx +886 -0
  26. package/Tests/App/Dashboard/CreateReviewStepRoleSummary.test.tsx +1250 -0
  27. package/Tests/App/Dashboard/CreateReviewStepSelectionSummary.test.tsx +738 -0
  28. package/Tests/App/Dashboard/DeclareIncidentFromAlert.test.ts +417 -0
  29. package/Tests/App/Dashboard/EntityDetailPanel.test.tsx +1948 -229
  30. package/Tests/App/Dashboard/EntityDetailPanelLifecycle.test.tsx +493 -0
  31. package/Tests/App/Dashboard/EntityDetailPanelNavigation.test.tsx +439 -0
  32. package/Tests/App/Dashboard/EventOverviewPages.test.tsx +292 -1
  33. package/Tests/App/Dashboard/EventStatusPanel.test.tsx +798 -2
  34. package/Tests/App/Dashboard/FetchStateAndSeverityElements.test.tsx +669 -0
  35. package/Tests/App/Dashboard/FetchUsers.test.tsx +230 -0
  36. package/Tests/App/Dashboard/IncidentCreateAcknowledgeAlerts.test.tsx +1611 -0
  37. package/Tests/App/Dashboard/InfrastructureExplorer.test.tsx +1365 -57
  38. package/Tests/App/Dashboard/InfrastructureGraph.test.tsx +964 -23
  39. package/Tests/App/Dashboard/InventoryRelationships.test.tsx +885 -0
  40. package/Tests/App/Dashboard/ServiceMapDatabaseLink.test.tsx +201 -15
  41. package/Tests/App/Dashboard/ServiceMapGraph.test.tsx +508 -36
  42. package/Tests/App/Dashboard/TopologyDataLifecycle.test.tsx +583 -0
  43. package/Tests/App/Dashboard/TopologyDataLoading.test.tsx +982 -218
  44. package/Tests/App/Dashboard/TopologyPageNavigation.test.tsx +818 -114
  45. package/Tests/Server/Infrastructure/Postgres/RenameInventoryItemMigration.test.ts +90 -21
  46. package/Tests/Server/Services/DomainService.test.ts +525 -0
  47. package/Tests/Server/Services/IncidentAlertAcknowledgeOnDeclare.test.ts +2630 -0
  48. package/Tests/Server/Services/IncidentAlertPostgres.test.ts +1625 -1
  49. package/Tests/Server/Services/IncidentDeclareAcknowledgeAlerts.test.ts +2189 -0
  50. package/Tests/Server/Services/InventoryItemServiceOverviewCounts.test.ts +345 -0
  51. package/Tests/Server/Services/InventoryOverviewPostgres.test.ts +254 -0
  52. package/Tests/Server/Services/IoTDeviceCredentialService.test.ts +819 -0
  53. package/Tests/Server/Services/LinkedAffectedResourcesCreatedFeed.test.ts +420 -0
  54. package/Tests/Server/Services/SloAffectedResourceCreatedFeed.test.ts +92 -36
  55. package/Tests/Server/Utils/AffectedResources/LinkedAffectedResources.test.ts +858 -0
  56. package/Tests/Server/Utils/Alert/AlertStateChangeAuthorization.test.ts +1172 -0
  57. package/Tests/Server/Utils/Topology/InventoryItemEntityKeyIndexMigration.test.ts +386 -0
  58. package/Tests/Server/Utils/Topology/InventoryItemEntityKeyIndexMigrationPostgres.test.ts +430 -0
  59. package/Tests/Server/Utils/Topology/TopologyActivityParityPostgres.test.ts +279 -0
  60. package/Tests/Server/Utils/Topology/TopologyConcurrencyLimiter.test.ts +534 -0
  61. package/Tests/Server/Utils/Topology/TopologyEstateGenerator.ts +624 -0
  62. package/Tests/Server/Utils/Topology/TopologyJsonResponse.test.ts +90 -0
  63. package/Tests/Server/Utils/Topology/TopologyQueries.test.ts +1634 -0
  64. package/Tests/Server/Utils/Topology/TopologyQueriesDifferentialPostgres.test.ts +683 -0
  65. package/Tests/Server/Utils/Topology/TopologyQueriesPostgres.test.ts +2624 -0
  66. package/Tests/Server/Utils/Topology/TopologyReference.ts +1018 -0
  67. package/Tests/Server/Utils/Topology/TopologyRequest.test.ts +643 -0
  68. package/Tests/Server/Utils/Topology/TopologyResponseCache.test.ts +305 -0
  69. package/Tests/Server/Utils/Topology/TopologySql.test.ts +973 -0
  70. package/Tests/Types/Topology/TopologyTypeRules.test.ts +176 -0
  71. package/Tests/Utils/Incident/IncidentFromAlerts.test.ts +302 -0
  72. package/Types/Incident/IncidentAlertLink.ts +19 -0
  73. package/Types/Telemetry/InventoryLiveness.ts +26 -0
  74. package/Types/Topology/TopologyApi.ts +428 -0
  75. package/Types/Topology/TopologyTypeRules.ts +191 -0
  76. package/Utils/Incident/IncidentFromAlerts.ts +78 -0
  77. package/build/dist/Models/DatabaseModels/InventoryItem.js +20 -11
  78. package/build/dist/Models/DatabaseModels/InventoryItem.js.map +1 -1
  79. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1795200000000-AddInventoryItemProjectEntityKeyIndex.js +165 -0
  80. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1795200000000-AddInventoryItemProjectEntityKeyIndex.js.map +1 -0
  81. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js +2 -0
  82. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js.map +1 -1
  83. package/build/dist/Server/Services/AlertService.js +21 -33
  84. package/build/dist/Server/Services/AlertService.js.map +1 -1
  85. package/build/dist/Server/Services/IncidentAlertService.js +457 -3
  86. package/build/dist/Server/Services/IncidentAlertService.js.map +1 -1
  87. package/build/dist/Server/Services/IncidentService.js +96 -42
  88. package/build/dist/Server/Services/IncidentService.js.map +1 -1
  89. package/build/dist/Server/Services/InventoryItemService.js +31 -0
  90. package/build/dist/Server/Services/InventoryItemService.js.map +1 -1
  91. package/build/dist/Server/Services/IoTDeviceCredentialService.js +12 -5
  92. package/build/dist/Server/Services/IoTDeviceCredentialService.js.map +1 -1
  93. package/build/dist/Server/Services/ScheduledMaintenanceService.js +37 -40
  94. package/build/dist/Server/Services/ScheduledMaintenanceService.js.map +1 -1
  95. package/build/dist/Server/Services/UserNotificationRuleService.js +55 -51
  96. package/build/dist/Server/Services/UserNotificationRuleService.js.map +1 -1
  97. package/build/dist/Server/Services/WorkspaceNotificationSummaryService.js +42 -25
  98. package/build/dist/Server/Services/WorkspaceNotificationSummaryService.js.map +1 -1
  99. package/build/dist/Server/Utils/AffectedResources/LinkedAffectedResources.js +405 -0
  100. package/build/dist/Server/Utils/AffectedResources/LinkedAffectedResources.js.map +1 -0
  101. package/build/dist/Server/Utils/Alert/AlertStateChangeAuthorization.js +112 -0
  102. package/build/dist/Server/Utils/Alert/AlertStateChangeAuthorization.js.map +1 -0
  103. package/build/dist/Server/Utils/Inventory/InventoryOverviewAggregation.js +81 -0
  104. package/build/dist/Server/Utils/Inventory/InventoryOverviewAggregation.js.map +1 -0
  105. package/build/dist/Server/Utils/Response.js +30 -0
  106. package/build/dist/Server/Utils/Response.js.map +1 -1
  107. package/build/dist/Server/Utils/Topology/TopologyConcurrencyLimiter.js +178 -0
  108. package/build/dist/Server/Utils/Topology/TopologyConcurrencyLimiter.js.map +1 -0
  109. package/build/dist/Server/Utils/Topology/TopologyQueries.js +884 -0
  110. package/build/dist/Server/Utils/Topology/TopologyQueries.js.map +1 -0
  111. package/build/dist/Server/Utils/Topology/TopologyRequest.js +275 -0
  112. package/build/dist/Server/Utils/Topology/TopologyRequest.js.map +1 -0
  113. package/build/dist/Server/Utils/Topology/TopologyResponseCache.js +146 -0
  114. package/build/dist/Server/Utils/Topology/TopologyResponseCache.js.map +1 -0
  115. package/build/dist/Server/Utils/Topology/TopologySql.js +688 -0
  116. package/build/dist/Server/Utils/Topology/TopologySql.js.map +1 -0
  117. package/build/dist/Types/Incident/IncidentAlertLink.js +17 -0
  118. package/build/dist/Types/Incident/IncidentAlertLink.js.map +1 -1
  119. package/build/dist/Types/Telemetry/InventoryLiveness.js +23 -0
  120. package/build/dist/Types/Telemetry/InventoryLiveness.js.map +1 -1
  121. package/build/dist/Types/Topology/TopologyApi.js +55 -0
  122. package/build/dist/Types/Topology/TopologyApi.js.map +1 -0
  123. package/build/dist/Types/Topology/TopologyTypeRules.js +165 -0
  124. package/build/dist/Types/Topology/TopologyTypeRules.js.map +1 -0
  125. package/build/dist/Utils/Incident/IncidentFromAlerts.js +38 -0
  126. package/build/dist/Utils/Incident/IncidentFromAlerts.js.map +1 -1
  127. package/package.json +1 -1
@@ -0,0 +1,405 @@
1
+ import QueryHelper from "../../Types/Database/QueryHelper";
2
+ import Alert from "../../../Models/DatabaseModels/Alert";
3
+ import Incident from "../../../Models/DatabaseModels/Incident";
4
+ import ScheduledMaintenance from "../../../Models/DatabaseModels/ScheduledMaintenance";
5
+ import URL from "../../../Types/API/URL";
6
+ import { escapeMarkdownInline } from "../../../Utils/Markdown/MarkdownEscape";
7
+ import { getSloAffectedResourceMarkdownLines, } from "../../../Utils/Slo/SloAffectedResourceMarkdown";
8
+ /*
9
+ * What an incident, alert or scheduled maintenance event affects, for the
10
+ * text the server writes about it: the "Resources Affected" section of its
11
+ * feed items, the Resources Affected row of its emails, and the workspace
12
+ * summaries.
13
+ *
14
+ * The dashboard's Affected Resources cards (AffectedResourcesDisplay) list
15
+ * every relation the record carries - monitors, hosts, clusters, container
16
+ * hosts, databases, services, SLOs. The server used to name the monitors
17
+ * only, so an SLO burn-rate alert's card named its SLO while its on-call
18
+ * email read "Resources Affected: No resources identified", and an incident
19
+ * raised against a host named nothing at all. Every one of those writers now
20
+ * reads the list from here, so they name what the cards show.
21
+ *
22
+ * Reads run as root - an owner or on-call email has no user session behind
23
+ * it - and are held to the record's own project twice: the record is only
24
+ * read inside that project, and a related row of any other project is left
25
+ * out. The write hooks reject cross-project links now, but rows saved before
26
+ * that check existed may still hold one, and naming it would put another
27
+ * project's resource into this project's feed, Slack and email.
28
+ *
29
+ * The caller hands over the service to read with, and the dashboard URL to
30
+ * link from. Those services import this module, and the owner-notification
31
+ * workers' tests replace them wholesale; importing them here would drag the
32
+ * whole service graph into every one of those suites.
33
+ */
34
+ export var LinkedAffectedResourceType;
35
+ (function (LinkedAffectedResourceType) {
36
+ LinkedAffectedResourceType["Monitor"] = "Monitor";
37
+ LinkedAffectedResourceType["Host"] = "Host";
38
+ LinkedAffectedResourceType["KubernetesCluster"] = "KubernetesCluster";
39
+ LinkedAffectedResourceType["DockerHost"] = "DockerHost";
40
+ LinkedAffectedResourceType["PodmanHost"] = "PodmanHost";
41
+ LinkedAffectedResourceType["ProxmoxCluster"] = "ProxmoxCluster";
42
+ LinkedAffectedResourceType["VMwareVCenter"] = "VMwareVCenter";
43
+ LinkedAffectedResourceType["CephCluster"] = "CephCluster";
44
+ LinkedAffectedResourceType["DockerSwarmCluster"] = "DockerSwarmCluster";
45
+ LinkedAffectedResourceType["IoTFleet"] = "IoTFleet";
46
+ LinkedAffectedResourceType["DatabaseServer"] = "DatabaseServer";
47
+ LinkedAffectedResourceType["NetworkSite"] = "NetworkSite";
48
+ LinkedAffectedResourceType["Service"] = "Service";
49
+ LinkedAffectedResourceType["ServiceLevelObjective"] = "ServiceLevelObjective";
50
+ })(LinkedAffectedResourceType || (LinkedAffectedResourceType = {}));
51
+ /*
52
+ * The categories AffectedResourcesDisplay renders, in the order it renders
53
+ * them, so a feed item lists resources the way the cards beside it do. The
54
+ * routes are the ones each resource's own getXLinkInDashboard builds (a test
55
+ * pins every one that exists); IoT fleets and network sites have none on the
56
+ * server, so theirs follow the dashboard's RouteMap.
57
+ *
58
+ * An alert has a single `monitor`; incidents and scheduled maintenance events
59
+ * have `monitors`. Each record kind is read for the columns its model has.
60
+ */
61
+ export const LINKED_AFFECTED_RESOURCE_RELATIONS = [
62
+ {
63
+ column: "monitors",
64
+ type: LinkedAffectedResourceType.Monitor,
65
+ label: "Monitor",
66
+ dashboardRoute: "monitors",
67
+ },
68
+ {
69
+ column: "monitor",
70
+ type: LinkedAffectedResourceType.Monitor,
71
+ label: "Monitor",
72
+ dashboardRoute: "monitors",
73
+ },
74
+ {
75
+ column: "hosts",
76
+ type: LinkedAffectedResourceType.Host,
77
+ label: "Host",
78
+ dashboardRoute: "host",
79
+ },
80
+ {
81
+ column: "kubernetesClusters",
82
+ type: LinkedAffectedResourceType.KubernetesCluster,
83
+ label: "Kubernetes Cluster",
84
+ dashboardRoute: "kubernetes",
85
+ },
86
+ {
87
+ column: "dockerHosts",
88
+ type: LinkedAffectedResourceType.DockerHost,
89
+ label: "Docker Host",
90
+ dashboardRoute: "docker",
91
+ },
92
+ {
93
+ column: "podmanHosts",
94
+ type: LinkedAffectedResourceType.PodmanHost,
95
+ label: "Podman Host",
96
+ dashboardRoute: "podman",
97
+ },
98
+ {
99
+ column: "proxmoxClusters",
100
+ type: LinkedAffectedResourceType.ProxmoxCluster,
101
+ label: "Proxmox Cluster",
102
+ dashboardRoute: "proxmox",
103
+ },
104
+ {
105
+ column: "vmwareVCenters",
106
+ type: LinkedAffectedResourceType.VMwareVCenter,
107
+ label: "VMware vCenter",
108
+ dashboardRoute: "vmware",
109
+ },
110
+ {
111
+ column: "cephClusters",
112
+ type: LinkedAffectedResourceType.CephCluster,
113
+ label: "Ceph Cluster",
114
+ dashboardRoute: "ceph",
115
+ },
116
+ {
117
+ column: "dockerSwarmClusters",
118
+ type: LinkedAffectedResourceType.DockerSwarmCluster,
119
+ label: "Docker Swarm Cluster",
120
+ dashboardRoute: "docker-swarm",
121
+ },
122
+ {
123
+ column: "iotFleets",
124
+ type: LinkedAffectedResourceType.IoTFleet,
125
+ label: "IoT Fleet",
126
+ dashboardRoute: "iot",
127
+ },
128
+ {
129
+ column: "databaseServers",
130
+ type: LinkedAffectedResourceType.DatabaseServer,
131
+ label: "Database",
132
+ dashboardRoute: "databases",
133
+ },
134
+ {
135
+ column: "networkSites",
136
+ type: LinkedAffectedResourceType.NetworkSite,
137
+ label: "Network Site",
138
+ dashboardRoute: "network-sites/view",
139
+ },
140
+ {
141
+ column: "services",
142
+ type: LinkedAffectedResourceType.Service,
143
+ label: "Service",
144
+ dashboardRoute: "service",
145
+ },
146
+ /*
147
+ * Last, as on the cards: an SLO is the objective measured over the
148
+ * resources above it rather than one of them.
149
+ */
150
+ {
151
+ column: "serviceLevelObjectives",
152
+ type: LinkedAffectedResourceType.ServiceLevelObjective,
153
+ label: "SLO",
154
+ dashboardRoute: "slos",
155
+ },
156
+ ];
157
+ function isSameProject(projectId, expected) {
158
+ if (!projectId) {
159
+ return false;
160
+ }
161
+ return (projectId.toString().trim().toLowerCase() ===
162
+ expected.toString().trim().toLowerCase());
163
+ }
164
+ export default class LinkedAffectedResources {
165
+ // The relations `model` carries, in display order.
166
+ static getRelations(model) {
167
+ return LINKED_AFFECTED_RESOURCE_RELATIONS.filter((relation) => {
168
+ return model.hasColumn(relation.column);
169
+ });
170
+ }
171
+ static async readForIncident(data) {
172
+ return await LinkedAffectedResources.readForIncidents({
173
+ service: data.service,
174
+ projectId: data.projectId,
175
+ incidentIds: [data.incidentId],
176
+ });
177
+ }
178
+ static async readForIncidents(data) {
179
+ return await LinkedAffectedResources.read({
180
+ service: data.service,
181
+ model: new Incident(),
182
+ projectId: data.projectId,
183
+ recordIds: data.incidentIds,
184
+ });
185
+ }
186
+ static async readForAlert(data) {
187
+ return await LinkedAffectedResources.readForAlerts({
188
+ service: data.service,
189
+ projectId: data.projectId,
190
+ alertIds: [data.alertId],
191
+ });
192
+ }
193
+ static async readForAlerts(data) {
194
+ return await LinkedAffectedResources.read({
195
+ service: data.service,
196
+ model: new Alert(),
197
+ projectId: data.projectId,
198
+ recordIds: data.alertIds,
199
+ });
200
+ }
201
+ static async readForScheduledMaintenance(data) {
202
+ return await LinkedAffectedResources.read({
203
+ service: data.service,
204
+ model: new ScheduledMaintenance(),
205
+ projectId: data.projectId,
206
+ recordIds: [data.scheduledMaintenanceId],
207
+ });
208
+ }
209
+ /*
210
+ * The resources linked to any of `recordIds`, merged into one list.
211
+ *
212
+ * One query per relation rather than one query selecting them all: the
213
+ * relations are many-to-many, and joining a dozen of them at once returns
214
+ * the product of their sizes - an incident on 50 monitors and 50 hosts
215
+ * would come back as 2,500 rows. Read one at a time, the rows add up.
216
+ */
217
+ static async read(data) {
218
+ const recordIds = [];
219
+ const seenRecordIds = new Set();
220
+ for (const recordId of data.recordIds) {
221
+ const key = (recordId === null || recordId === void 0 ? void 0 : recordId.toString()) || "";
222
+ if (!key || seenRecordIds.has(key)) {
223
+ continue;
224
+ }
225
+ seenRecordIds.add(key);
226
+ recordIds.push(recordId);
227
+ }
228
+ if (recordIds.length === 0) {
229
+ return [];
230
+ }
231
+ const rowsPerRelation = await Promise.all(LinkedAffectedResources.getRelations(data.model).map((relation) => {
232
+ return data.service.findAllBy({
233
+ query: {
234
+ _id: QueryHelper.any(recordIds),
235
+ projectId: data.projectId,
236
+ },
237
+ select: {
238
+ _id: true,
239
+ projectId: true,
240
+ [relation.column]: {
241
+ _id: true,
242
+ name: true,
243
+ projectId: true,
244
+ },
245
+ },
246
+ props: {
247
+ isRoot: true,
248
+ },
249
+ });
250
+ }));
251
+ return LinkedAffectedResources.collect({
252
+ projectId: data.projectId,
253
+ records: rowsPerRelation.flatMap((rows) => {
254
+ return rows || [];
255
+ }),
256
+ });
257
+ }
258
+ /*
259
+ * The resources on already-read records, in display order and without
260
+ * repeats. A related row is kept only when it has an id and belongs to
261
+ * `projectId`; a row whose project was not read cannot be shown to belong
262
+ * here, so it is left out too - which also makes a caller that drops
263
+ * projectId from its select fail loudly in tests rather than quietly
264
+ * print nothing.
265
+ */
266
+ static collect(data) {
267
+ var _a, _b;
268
+ const resources = [];
269
+ const seen = new Set();
270
+ const records = data.records.filter((record) => {
271
+ if (!record) {
272
+ return false;
273
+ }
274
+ // A record read without its project is taken to be the caller's.
275
+ return (!record.projectId || isSameProject(record.projectId, data.projectId));
276
+ });
277
+ for (const relation of LINKED_AFFECTED_RESOURCE_RELATIONS) {
278
+ for (const record of records) {
279
+ const value = record[relation.column];
280
+ const rows = Array.isArray(value)
281
+ ? value
282
+ : value
283
+ ? [value]
284
+ : [];
285
+ for (const row of rows) {
286
+ const id = ((_a = row === null || row === void 0 ? void 0 : row._id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
287
+ if (!row || !id || !isSameProject(row.projectId, data.projectId)) {
288
+ continue;
289
+ }
290
+ const key = `${relation.type}:${id}`;
291
+ if (seen.has(key)) {
292
+ continue;
293
+ }
294
+ seen.add(key);
295
+ resources.push({
296
+ type: relation.type,
297
+ id: id,
298
+ name: ((_b = row.name) === null || _b === void 0 ? void 0 : _b.toString()) || "",
299
+ });
300
+ }
301
+ }
302
+ }
303
+ return resources;
304
+ }
305
+ /*
306
+ * The names, for plain-text surfaces: emails and workspace summaries.
307
+ *
308
+ * `seriesSummary` is an alert's series identity - the pod or container a
309
+ * grouped monitor raised it for (SeriesLabelDisplay.buildInlineSummary).
310
+ * It names what broke more precisely than the monitor does, so it takes
311
+ * the monitor's place at the head of the list rather than joining it.
312
+ *
313
+ * A name that repeats (a monitor and a host both called "web-01") is
314
+ * printed once: this is a sentence, not a table.
315
+ */
316
+ static getNames(data) {
317
+ var _a;
318
+ const names = [];
319
+ const seenNames = new Set();
320
+ const seriesSummary = ((_a = data.seriesSummary) === null || _a === void 0 ? void 0 : _a.trim()) || "";
321
+ const addName = (name) => {
322
+ const trimmed = name.trim();
323
+ if (!trimmed || seenNames.has(trimmed)) {
324
+ return;
325
+ }
326
+ seenNames.add(trimmed);
327
+ names.push(trimmed);
328
+ };
329
+ addName(seriesSummary);
330
+ for (const resource of data.resources) {
331
+ if (seriesSummary &&
332
+ resource.type === LinkedAffectedResourceType.Monitor) {
333
+ continue;
334
+ }
335
+ addName(resource.name);
336
+ }
337
+ return names;
338
+ }
339
+ // getNames joined with ", ", or `fallback` when there are none.
340
+ static getText(data) {
341
+ return (LinkedAffectedResources.getNames({
342
+ resources: data.resources,
343
+ seriesSummary: data.seriesSummary,
344
+ }).join(", ") || data.fallback);
345
+ }
346
+ static getDashboardUrl(data) {
347
+ const relation = LinkedAffectedResources.getRelationForType(data.resource.type);
348
+ // URL.addRoute mutates, and the caller reuses its dashboard URL.
349
+ return URL.fromString(data.dashboardUrl.toString()).addRoute(`/${data.projectId.toString()}/${relation.dashboardRoute}/${data.resource.id}`);
350
+ }
351
+ /*
352
+ * The bullets under a feed item's "🌎 Resources Affected" header.
353
+ *
354
+ * A monitor keeps the bullet the created feeds have always printed,
355
+ * `- [<name>](<monitor link>)`, and an SLO keeps `- [SLO <name>](<link>)`
356
+ * from getSloAffectedResourceMarkdownLines. Every other resource follows
357
+ * the SLO's shape, `- [Host <name>](<link>)`, so the reader can tell a host
358
+ * from a cluster from a service.
359
+ *
360
+ * Those names are escaped: feeds render without safe mode and the same
361
+ * markdown goes to Slack and Teams, and a host or cluster name can come
362
+ * from an agent rather than from someone typing it.
363
+ */
364
+ static getMarkdownLines(data) {
365
+ const lines = [];
366
+ const slos = [];
367
+ for (const resource of data.resources) {
368
+ if (resource.type === LinkedAffectedResourceType.ServiceLevelObjective) {
369
+ slos.push({
370
+ _id: resource.id,
371
+ name: resource.name,
372
+ // Already held to this project by collect.
373
+ projectId: data.projectId,
374
+ });
375
+ continue;
376
+ }
377
+ const link = LinkedAffectedResources.getDashboardUrl({
378
+ dashboardUrl: data.dashboardUrl,
379
+ projectId: data.projectId,
380
+ resource: resource,
381
+ }).toString();
382
+ if (resource.type === LinkedAffectedResourceType.Monitor) {
383
+ lines.push(`- [${resource.name}](${link})`);
384
+ continue;
385
+ }
386
+ const label = LinkedAffectedResources.getRelationForType(resource.type).label;
387
+ const escapedName = escapeMarkdownInline(resource.name).trim();
388
+ lines.push(`- [${escapedName ? `${label} ${escapedName}` : label}](${link})`);
389
+ }
390
+ // SLOs are last in the table, so appending them keeps the order.
391
+ lines.push(...getSloAffectedResourceMarkdownLines({
392
+ dashboardUrl: data.dashboardUrl,
393
+ projectId: data.projectId,
394
+ serviceLevelObjectives: slos,
395
+ }));
396
+ return lines;
397
+ }
398
+ static getRelationForType(type) {
399
+ // Every type has at least one entry, so this always finds one.
400
+ return LINKED_AFFECTED_RESOURCE_RELATIONS.find((relation) => {
401
+ return relation.type === type;
402
+ });
403
+ }
404
+ }
405
+ //# sourceMappingURL=LinkedAffectedResources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LinkedAffectedResources.js","sourceRoot":"","sources":["../../../../../Server/Utils/AffectedResources/LinkedAffectedResources.ts"],"names":[],"mappings":"AAEA,OAAO,WAAW,MAAM,kCAAkC,CAAC;AAE3D,OAAO,KAAK,MAAM,sCAAsC,CAAC;AAEzD,OAAO,QAAQ,MAAM,yCAAyC,CAAC;AAC/D,OAAO,oBAAoB,MAAM,qDAAqD,CAAC;AACvF,OAAO,GAAG,MAAM,wBAAwB,CAAC;AAEzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAC9E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,CAAC,IAAI,EAAE,CAAC;YAEvE,KAAK,CAAC,IAAI,CACR,MAAM,WAAW,CAAC,CAAC,CAAC,GAAG,KAAK,IAAI,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,KAAK,IAAI,GAAG,CAClE,CAAC;QACJ,CAAC;QAED,iEAAiE;QACjE,KAAK,CAAC,IAAI,CACR,GAAG,mCAAmC,CAAC;YACrC,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,sBAAsB,EAAE,IAAI;SAC7B,CAAC,CACH,CAAC;QAEF,OAAO,KAAK,CAAC;IACf,CAAC;IAEO,MAAM,CAAC,kBAAkB,CAC/B,IAAgC;QAEhC,+DAA+D;QAC/D,OAAO,kCAAkC,CAAC,IAAI,CAC5C,CAAC,QAAwC,EAAE,EAAE;YAC3C,OAAO,QAAQ,CAAC,IAAI,KAAK,IAAI,CAAC;QAChC,CAAC,CACD,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,112 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import Alert from "../../../Models/DatabaseModels/Alert";
11
+ import AlertStateTimeline from "../../../Models/DatabaseModels/AlertStateTimeline";
12
+ import { LIMIT_PER_PROJECT } from "../../../Types/Database/LimitMax";
13
+ import NotAuthorizedException from "../../../Types/Exception/NotAuthorizedException";
14
+ import ObjectID from "../../../Types/ObjectID";
15
+ import AlertService from "../../Services/AlertService";
16
+ import ModelPermission from "../../Types/Database/Permissions/Index";
17
+ import QueryHelper from "../../Types/Database/QueryHelper";
18
+ import { applyAlertSelfPrivacyFilter } from "./AlertPrivacyFilter";
19
+ import CaptureSpan from "../Telemetry/CaptureSpan";
20
+ /*
21
+ * Whether a caller may change the state of a set of alerts - acknowledge
22
+ * them, say - when that change is going to be written for them as root.
23
+ *
24
+ * Changing an alert's state from its own page takes two writes as the caller:
25
+ * a new AlertStateTimeline row (table and column permissions only), and then
26
+ * the alert's currentAlertStateId, which is an Alert UPDATE and so is narrowed
27
+ * by the caller's label scope, Owned scope and alert privacy. Being able to
28
+ * read an alert is not enough: a Viewer who is also an AlertMember for one
29
+ * label can read every alert but change the state of only some. A root write
30
+ * skips both, so this checks both, for every alert, before anything is
31
+ * written - the same rule the Microsoft Teams acknowledge action applies to
32
+ * one alert.
33
+ */
34
+ export default class AlertStateChangeAuthorization {
35
+ static async assertCanChangeStateOfAlerts(data) {
36
+ if (data.props.isRoot || data.alertIds.length === 0) {
37
+ return;
38
+ }
39
+ const probe = new AlertStateTimeline();
40
+ probe.projectId = data.projectId;
41
+ probe.alertId = data.alertIds[0];
42
+ probe.alertStateId = ObjectID.generate();
43
+ ModelPermission.checkCreatePermissions(AlertStateTimeline, probe, data.props);
44
+ const alertQuery = {
45
+ _id: QueryHelper.any(data.alertIds),
46
+ projectId: data.projectId,
47
+ };
48
+ /*
49
+ * Labelled block and allow rules are decided per record, from the
50
+ * record's labels.
51
+ */
52
+ const alerts = await AlertService.findBy({
53
+ query: alertQuery,
54
+ select: {
55
+ _id: true,
56
+ labels: {
57
+ _id: true,
58
+ name: true,
59
+ },
60
+ },
61
+ limit: LIMIT_PER_PROJECT,
62
+ skip: 0,
63
+ props: {
64
+ isRoot: true,
65
+ },
66
+ });
67
+ for (const alert of alerts) {
68
+ await ModelPermission.checkUpdatePermissionByModel({
69
+ modelType: Alert,
70
+ fetchModelWithAccessControlIds: async () => {
71
+ return alert;
72
+ },
73
+ props: data.props,
74
+ });
75
+ }
76
+ /*
77
+ * The caller's own update scope (labels, Owned, privacy) as a query:
78
+ * every alert must still be in it.
79
+ */
80
+ const permittedQuery = await ModelPermission.checkUpdateQueryPermissions(Alert, alertQuery, {
81
+ currentAlertStateId: ObjectID.getZeroObjectID(),
82
+ }, data.props);
83
+ const permittedAlerts = await AlertService.findBy({
84
+ query: applyAlertSelfPrivacyFilter(permittedQuery, data.props),
85
+ select: {
86
+ _id: true,
87
+ },
88
+ limit: LIMIT_PER_PROJECT,
89
+ skip: 0,
90
+ props: {
91
+ isRoot: true,
92
+ },
93
+ });
94
+ const permittedIds = new Set(permittedAlerts.map((alert) => {
95
+ var _a;
96
+ return ((_a = alert._id) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase()) || "";
97
+ }));
98
+ const allPermitted = data.alertIds.every((alertId) => {
99
+ return permittedIds.has(alertId.toString().toLowerCase());
100
+ });
101
+ if (!allPermitted) {
102
+ throw new NotAuthorizedException("You do not have permission to change the state of one or more of these alerts.");
103
+ }
104
+ }
105
+ }
106
+ __decorate([
107
+ CaptureSpan(),
108
+ __metadata("design:type", Function),
109
+ __metadata("design:paramtypes", [Object]),
110
+ __metadata("design:returntype", Promise)
111
+ ], AlertStateChangeAuthorization, "assertCanChangeStateOfAlerts", null);
112
+ //# sourceMappingURL=AlertStateChangeAuthorization.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AlertStateChangeAuthorization.js","sourceRoot":"","sources":["../../../../../Server/Utils/Alert/AlertStateChangeAuthorization.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,KAAK,MAAM,sCAAsC,CAAC;AACzD,OAAO,kBAAkB,MAAM,mDAAmD,CAAC;AAEnF,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,sBAAsB,MAAM,iDAAiD,CAAC;AACrF,OAAO,QAAQ,MAAM,yBAA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,CAC9B,gFAAgF,CACjF,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AAnGqB;IADnB,WAAW,EAAE;;;;uEAmGb"}
@@ -0,0 +1,81 @@
1
+ import AggregateResultUtil from "../../Types/Database/AggregateResultUtil";
2
+ import EntitySource from "../../../Types/Telemetry/EntitySource";
3
+ import { InventoryLiveness, getInventoryLivenessSql, } from "../../../Types/Telemetry/InventoryLiveness";
4
+ /*
5
+ * The Inventory Overview's numbers: the five summary tiles and the per-type
6
+ * breakdown.
7
+ *
8
+ * These used to be folded in the browser from one list read capped at
9
+ * LIMIT_PER_PROJECT, so a project past ten thousand items saw tiles and a
10
+ * breakdown describing whichever ten thousand had been seen most recently,
11
+ * with nothing on the page saying so. They are counted in Postgres instead,
12
+ * in ONE grouped statement: the tiles are sums over the same per-type groups
13
+ * the breakdown lists, so the two are views of one snapshot and cannot
14
+ * disagree.
15
+ *
16
+ * Every tile drills into the Items list, and each filter below is the exact
17
+ * narrowing that tile's list applies — the source facet, or the source facet
18
+ * plus the Stale status facet, whose SQL is the same getInventoryLivenessSql
19
+ * the `inventoryStatus` virtual column is built from.
20
+ *
21
+ * Kept apart from InventoryItemService so the dashboard's tile tests and the
22
+ * Postgres test can use the same columns without loading the service.
23
+ */
24
+ export const INVENTORY_OVERVIEW_GROUP_BY = [
25
+ { expression: `"InventoryItem"."entityType"`, alias: "entityType" },
26
+ ];
27
+ export const INVENTORY_OVERVIEW_SELECT = [
28
+ { expression: `COUNT(*)`, alias: "itemCount" },
29
+ {
30
+ expression: `COUNT(*) FILTER (WHERE "InventoryItem"."source" = '${EntitySource.Discovered}')`,
31
+ alias: "discoveredCount",
32
+ },
33
+ {
34
+ expression: `COUNT(*) FILTER (WHERE "InventoryItem"."source" = '${EntitySource.Inventory}')`,
35
+ alias: "mirroredCount",
36
+ },
37
+ {
38
+ expression: `COUNT(*) FILTER (WHERE "InventoryItem"."source" = '${EntitySource.Manual}')`,
39
+ alias: "manualCount",
40
+ },
41
+ {
42
+ // Only discovered rows can be stale; the shared rule says NotTracked for the rest.
43
+ expression: `COUNT(*) FILTER (WHERE (${getInventoryLivenessSql(`"InventoryItem"`)}) = '${InventoryLiveness.Stale}')`,
44
+ alias: "staleCount",
45
+ },
46
+ ];
47
+ /**
48
+ * Sum the per-type groups into the tile counts, and key the groups by type
49
+ * for the breakdown.
50
+ *
51
+ * `total` counts every row, including rows whose source this build does not
52
+ * recognise — they land in none of the three source buckets, which is why
53
+ * those are not expected to sum to the total. A group with no type still
54
+ * counts towards every tile; it is only left out of the breakdown, which has
55
+ * no row to put it in.
56
+ */
57
+ export function readInventoryOverviewGroups(rows) {
58
+ const counts = {
59
+ total: 0,
60
+ discovered: 0,
61
+ mirrored: 0,
62
+ manual: 0,
63
+ stale: 0,
64
+ countsByType: {},
65
+ };
66
+ for (const row of rows) {
67
+ const itemCount = AggregateResultUtil.toNumber(row, "itemCount");
68
+ counts.total += itemCount;
69
+ counts.discovered += AggregateResultUtil.toNumber(row, "discoveredCount");
70
+ counts.mirrored += AggregateResultUtil.toNumber(row, "mirroredCount");
71
+ counts.manual += AggregateResultUtil.toNumber(row, "manualCount");
72
+ counts.stale += AggregateResultUtil.toNumber(row, "staleCount");
73
+ const entityType = AggregateResultUtil.toStringOrNull(row, "entityType");
74
+ if (entityType && itemCount > 0) {
75
+ counts.countsByType[entityType] =
76
+ (counts.countsByType[entityType] || 0) + itemCount;
77
+ }
78
+ }
79
+ return counts;
80
+ }
81
+ //# sourceMappingURL=InventoryOverviewAggregation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InventoryOverviewAggregation.js","sourceRoot":"","sources":["../../../../../Server/Utils/Inventory/InventoryOverviewAggregation.ts"],"names":[],"mappings":"AAIA,OAAO,mBAAmB,MAAM,0CAA0C,CAAC;AAE3E,OAAO,YAAY,MAAM,uCAAuC,CAAC;AACjE,OAAO,EACL,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AAEpD;;;;;;;;;;;;;;;;;;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M,CAAC,MAAM,IAAI,mBAAmB,CAAC,QAAQ,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;QAClE,MAAM,CAAC,KAAK,IAAI,mBAAmB,CAAC,QAAQ,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;QAEhE,MAAM,UAAU,GAAkB,mBAAmB,CAAC,cAAc,CAClE,GAAG,EACH,YAAY,CACb,CAAC;QAEF,IAAI,UAAU,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;YAChC,MAAM,CAAC,YAAY,CAAC,UAAU,CAAC;gBAC7B,CAAC,MAAM,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,GAAG,SAAS,CAAC;QACvD,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -275,6 +275,30 @@ export default class Response {
275
275
  .status((options === null || options === void 0 ? void 0 : options.statusCode) ? options === null || options === void 0 ? void 0 : options.statusCode.toNumber() : 200)
276
276
  .send(item);
277
277
  }
278
+ /*
279
+ * Send a body that is ALREADY serialized JSON, as is.
280
+ *
281
+ * For responses built once and handed out many times (the Topology maps
282
+ * cache their serialized payload): sendJsonObjectResponse would parse
283
+ * nothing but re-stringify a multi-megabyte object on every hit, and
284
+ * res.send would hash the whole body for an ETag nobody can use on a POST.
285
+ * writeHead + end skips both, the way sendHtmlResponse does.
286
+ *
287
+ * no-store: the body is one project's inventory, read under the caller's
288
+ * permissions. The audit log gets its size, never the payload.
289
+ */
290
+ static sendJsonStringResponse(_req, res, json) {
291
+ const oneUptimeResponse = res;
292
+ Response.setNoCacheHeaders(oneUptimeResponse);
293
+ oneUptimeResponse.logBody = {
294
+ contentType: "application/json",
295
+ characters: json.length,
296
+ };
297
+ oneUptimeResponse.writeHead(200, {
298
+ "Content-Type": "application/json; charset=utf-8",
299
+ });
300
+ oneUptimeResponse.end(json);
301
+ }
278
302
  static sendTextResponse(_req, res, text) {
279
303
  const oneUptimeResponse = res;
280
304
  oneUptimeResponse.logBody = { text: text };
@@ -457,6 +481,12 @@ __decorate([
457
481
  __metadata("design:paramtypes", [Object, Object, Object, Object]),
458
482
  __metadata("design:returntype", void 0)
459
483
  ], Response, "sendJsonObjectResponse", null);
484
+ __decorate([
485
+ CaptureSpan(),
486
+ __metadata("design:type", Function),
487
+ __metadata("design:paramtypes", [Object, Object, String]),
488
+ __metadata("design:returntype", void 0)
489
+ ], Response, "sendJsonStringResponse", null);
460
490
  __decorate([
461
491
  CaptureSpan(),
462
492
  __metadata("design:type", Function),