@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
@@ -18,6 +18,8 @@ import IncidentStateTimeline from "../../Models/DatabaseModels/IncidentStateTime
18
18
  import AlertStateTimeline from "../../Models/DatabaseModels/AlertStateTimeline";
19
19
  import Label from "../../Models/DatabaseModels/Label";
20
20
  import Monitor from "../../Models/DatabaseModels/Monitor";
21
+ import LinkedAffectedResources from "../Utils/AffectedResources/LinkedAffectedResources";
22
+ import { escapeMarkdownInline } from "../../Utils/Markdown/MarkdownEscape";
21
23
  import WorkspaceNotificationLogService from "./WorkspaceNotificationLogService";
22
24
  import WorkspaceNotificationStatus from "../../Types/Workspace/WorkspaceNotificationStatus";
23
25
  import WorkspaceNotificationActionType from "../../Types/Workspace/WorkspaceNotificationActionType";
@@ -212,6 +214,18 @@ export class Service extends DatabaseService<WorkspaceNotificationSummary> {
212
214
  return `[${text}](${url})`;
213
215
  }
214
216
 
217
+ /*
218
+ * Resource names are escaped: a host or cluster name can come from an
219
+ * agent rather than from someone typing it, and this text is markdown.
220
+ */
221
+ private static joinNames(names: Array<string>): string {
222
+ return names
223
+ .map((name: string): string => {
224
+ return escapeMarkdownInline(name);
225
+ })
226
+ .join(", ");
227
+ }
228
+
215
229
  private static formatDuration(totalMinutes: number): string {
216
230
  if (totalMinutes < 1) {
217
231
  return "< 1m";
@@ -761,20 +775,20 @@ export class Service extends DatabaseService<WorkspaceNotificationSummary> {
761
775
  if (
762
776
  Service.has(items, WorkspaceNotificationSummaryItem.ResourcesAffected)
763
777
  ) {
764
- const names: Set<string> = new Set();
765
- for (const inc of incidents) {
766
- if (inc.monitors) {
767
- for (const m of inc.monitors) {
768
- if (m.name) {
769
- names.add(m.name);
770
- }
771
- }
772
- }
773
- }
774
- if (names.size > 0) {
778
+ // Every resource the period's incidents are linked to, not only monitors.
779
+ const names: Array<string> = LinkedAffectedResources.getNames({
780
+ resources: await LinkedAffectedResources.readForIncidents({
781
+ service: IncidentService,
782
+ projectId,
783
+ incidentIds: incidents.map((inc: Incident): ObjectID => {
784
+ return inc.id!;
785
+ }),
786
+ }),
787
+ });
788
+ if (names.length > 0) {
775
789
  blocks.push(
776
790
  Service.md(
777
- `${Service.bold(`Resources Affected (${names.size}):`)} ${Array.from(names).join(", ")}`,
791
+ `${Service.bold(`Resources Affected (${names.length}):`)} ${Service.joinNames(names)}`,
778
792
  ),
779
793
  );
780
794
  }
@@ -1203,16 +1217,20 @@ export class Service extends DatabaseService<WorkspaceNotificationSummary> {
1203
1217
  if (
1204
1218
  Service.has(items, WorkspaceNotificationSummaryItem.ResourcesAffected)
1205
1219
  ) {
1206
- const names: Set<string> = new Set();
1207
- for (const a of alerts) {
1208
- if (a.monitor?.name) {
1209
- names.add(a.monitor.name);
1210
- }
1211
- }
1212
- if (names.size > 0) {
1220
+ // Every resource the period's alerts are linked to, not only monitors.
1221
+ const names: Array<string> = LinkedAffectedResources.getNames({
1222
+ resources: await LinkedAffectedResources.readForAlerts({
1223
+ service: AlertService,
1224
+ projectId,
1225
+ alertIds: alerts.map((a: Alert): ObjectID => {
1226
+ return a.id!;
1227
+ }),
1228
+ }),
1229
+ });
1230
+ if (names.length > 0) {
1213
1231
  blocks.push(
1214
1232
  Service.md(
1215
- `${Service.bold(`Resources Affected (${names.size}):`)} ${Array.from(names).join(", ")}`,
1233
+ `${Service.bold(`Resources Affected (${names.length}):`)} ${Service.joinNames(names)}`,
1216
1234
  ),
1217
1235
  );
1218
1236
  }
@@ -0,0 +1,576 @@
1
+ import FindAllBy from "../../Types/Database/FindAllBy";
2
+ import Query from "../../Types/Database/Query";
3
+ import QueryHelper from "../../Types/Database/QueryHelper";
4
+ import Select from "../../Types/Database/Select";
5
+ import Alert from "../../../Models/DatabaseModels/Alert";
6
+ import DatabaseBaseModel from "../../../Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel";
7
+ import Incident from "../../../Models/DatabaseModels/Incident";
8
+ import ScheduledMaintenance from "../../../Models/DatabaseModels/ScheduledMaintenance";
9
+ import URL from "../../../Types/API/URL";
10
+ import ObjectID from "../../../Types/ObjectID";
11
+ import { escapeMarkdownInline } from "../../../Utils/Markdown/MarkdownEscape";
12
+ import {
13
+ getSloAffectedResourceMarkdownLines,
14
+ SloAffectedResourceLinkSubject,
15
+ } from "../../../Utils/Slo/SloAffectedResourceMarkdown";
16
+
17
+ /*
18
+ * What an incident, alert or scheduled maintenance event affects, for the
19
+ * text the server writes about it: the "Resources Affected" section of its
20
+ * feed items, the Resources Affected row of its emails, and the workspace
21
+ * summaries.
22
+ *
23
+ * The dashboard's Affected Resources cards (AffectedResourcesDisplay) list
24
+ * every relation the record carries - monitors, hosts, clusters, container
25
+ * hosts, databases, services, SLOs. The server used to name the monitors
26
+ * only, so an SLO burn-rate alert's card named its SLO while its on-call
27
+ * email read "Resources Affected: No resources identified", and an incident
28
+ * raised against a host named nothing at all. Every one of those writers now
29
+ * reads the list from here, so they name what the cards show.
30
+ *
31
+ * Reads run as root - an owner or on-call email has no user session behind
32
+ * it - and are held to the record's own project twice: the record is only
33
+ * read inside that project, and a related row of any other project is left
34
+ * out. The write hooks reject cross-project links now, but rows saved before
35
+ * that check existed may still hold one, and naming it would put another
36
+ * project's resource into this project's feed, Slack and email.
37
+ *
38
+ * The caller hands over the service to read with, and the dashboard URL to
39
+ * link from. Those services import this module, and the owner-notification
40
+ * workers' tests replace them wholesale; importing them here would drag the
41
+ * whole service graph into every one of those suites.
42
+ */
43
+
44
+ export enum LinkedAffectedResourceType {
45
+ Monitor = "Monitor",
46
+ Host = "Host",
47
+ KubernetesCluster = "KubernetesCluster",
48
+ DockerHost = "DockerHost",
49
+ PodmanHost = "PodmanHost",
50
+ ProxmoxCluster = "ProxmoxCluster",
51
+ VMwareVCenter = "VMwareVCenter",
52
+ CephCluster = "CephCluster",
53
+ DockerSwarmCluster = "DockerSwarmCluster",
54
+ IoTFleet = "IoTFleet",
55
+ DatabaseServer = "DatabaseServer",
56
+ NetworkSite = "NetworkSite",
57
+ Service = "Service",
58
+ ServiceLevelObjective = "ServiceLevelObjective",
59
+ }
60
+
61
+ export interface LinkedAffectedResource {
62
+ type: LinkedAffectedResourceType;
63
+ id: string;
64
+ name: string;
65
+ }
66
+
67
+ export interface LinkedAffectedResourceRelation {
68
+ // The relation column on Incident / Alert / ScheduledMaintenance.
69
+ column: string;
70
+ type: LinkedAffectedResourceType;
71
+ // Leads the feed bullet, e.g. "[Host web-01](...)".
72
+ label: string;
73
+ // The dashboard route after `/<projectId>/`, ending just before the id.
74
+ dashboardRoute: string;
75
+ }
76
+
77
+ /*
78
+ * The categories AffectedResourcesDisplay renders, in the order it renders
79
+ * them, so a feed item lists resources the way the cards beside it do. The
80
+ * routes are the ones each resource's own getXLinkInDashboard builds (a test
81
+ * pins every one that exists); IoT fleets and network sites have none on the
82
+ * server, so theirs follow the dashboard's RouteMap.
83
+ *
84
+ * An alert has a single `monitor`; incidents and scheduled maintenance events
85
+ * have `monitors`. Each record kind is read for the columns its model has.
86
+ */
87
+ export const LINKED_AFFECTED_RESOURCE_RELATIONS: ReadonlyArray<LinkedAffectedResourceRelation> =
88
+ [
89
+ {
90
+ column: "monitors",
91
+ type: LinkedAffectedResourceType.Monitor,
92
+ label: "Monitor",
93
+ dashboardRoute: "monitors",
94
+ },
95
+ {
96
+ column: "monitor",
97
+ type: LinkedAffectedResourceType.Monitor,
98
+ label: "Monitor",
99
+ dashboardRoute: "monitors",
100
+ },
101
+ {
102
+ column: "hosts",
103
+ type: LinkedAffectedResourceType.Host,
104
+ label: "Host",
105
+ dashboardRoute: "host",
106
+ },
107
+ {
108
+ column: "kubernetesClusters",
109
+ type: LinkedAffectedResourceType.KubernetesCluster,
110
+ label: "Kubernetes Cluster",
111
+ dashboardRoute: "kubernetes",
112
+ },
113
+ {
114
+ column: "dockerHosts",
115
+ type: LinkedAffectedResourceType.DockerHost,
116
+ label: "Docker Host",
117
+ dashboardRoute: "docker",
118
+ },
119
+ {
120
+ column: "podmanHosts",
121
+ type: LinkedAffectedResourceType.PodmanHost,
122
+ label: "Podman Host",
123
+ dashboardRoute: "podman",
124
+ },
125
+ {
126
+ column: "proxmoxClusters",
127
+ type: LinkedAffectedResourceType.ProxmoxCluster,
128
+ label: "Proxmox Cluster",
129
+ dashboardRoute: "proxmox",
130
+ },
131
+ {
132
+ column: "vmwareVCenters",
133
+ type: LinkedAffectedResourceType.VMwareVCenter,
134
+ label: "VMware vCenter",
135
+ dashboardRoute: "vmware",
136
+ },
137
+ {
138
+ column: "cephClusters",
139
+ type: LinkedAffectedResourceType.CephCluster,
140
+ label: "Ceph Cluster",
141
+ dashboardRoute: "ceph",
142
+ },
143
+ {
144
+ column: "dockerSwarmClusters",
145
+ type: LinkedAffectedResourceType.DockerSwarmCluster,
146
+ label: "Docker Swarm Cluster",
147
+ dashboardRoute: "docker-swarm",
148
+ },
149
+ {
150
+ column: "iotFleets",
151
+ type: LinkedAffectedResourceType.IoTFleet,
152
+ label: "IoT Fleet",
153
+ dashboardRoute: "iot",
154
+ },
155
+ {
156
+ column: "databaseServers",
157
+ type: LinkedAffectedResourceType.DatabaseServer,
158
+ label: "Database",
159
+ dashboardRoute: "databases",
160
+ },
161
+ {
162
+ column: "networkSites",
163
+ type: LinkedAffectedResourceType.NetworkSite,
164
+ label: "Network Site",
165
+ dashboardRoute: "network-sites/view",
166
+ },
167
+ {
168
+ column: "services",
169
+ type: LinkedAffectedResourceType.Service,
170
+ label: "Service",
171
+ dashboardRoute: "service",
172
+ },
173
+ /*
174
+ * Last, as on the cards: an SLO is the objective measured over the
175
+ * resources above it rather than one of them.
176
+ */
177
+ {
178
+ column: "serviceLevelObjectives",
179
+ type: LinkedAffectedResourceType.ServiceLevelObjective,
180
+ label: "SLO",
181
+ dashboardRoute: "slos",
182
+ },
183
+ ];
184
+
185
+ // Structural, so a model instance and a plain relation row both fit.
186
+ interface RelatedRow {
187
+ _id?: string | ObjectID | undefined | null;
188
+ name?: string | undefined | null;
189
+ projectId?: ObjectID | string | undefined | null;
190
+ }
191
+
192
+ type RecordWithRelations = {
193
+ projectId?: ObjectID | string | undefined | null;
194
+ } & Partial<Record<string, unknown>>;
195
+
196
+ // The one method read here - IncidentService, AlertService and so on.
197
+ export interface LinkedAffectedResourceReader<
198
+ TBaseModel extends DatabaseBaseModel,
199
+ > {
200
+ findAllBy(findAllBy: FindAllBy<TBaseModel>): Promise<Array<TBaseModel>>;
201
+ }
202
+
203
+ function isSameProject(
204
+ projectId: ObjectID | string | undefined | null,
205
+ expected: ObjectID,
206
+ ): boolean {
207
+ if (!projectId) {
208
+ return false;
209
+ }
210
+
211
+ return (
212
+ projectId.toString().trim().toLowerCase() ===
213
+ expected.toString().trim().toLowerCase()
214
+ );
215
+ }
216
+
217
+ export default class LinkedAffectedResources {
218
+ // The relations `model` carries, in display order.
219
+ public static getRelations(
220
+ model: DatabaseBaseModel,
221
+ ): Array<LinkedAffectedResourceRelation> {
222
+ return LINKED_AFFECTED_RESOURCE_RELATIONS.filter(
223
+ (relation: LinkedAffectedResourceRelation) => {
224
+ return model.hasColumn(relation.column);
225
+ },
226
+ );
227
+ }
228
+
229
+ public static async readForIncident(data: {
230
+ service: LinkedAffectedResourceReader<Incident>;
231
+ projectId: ObjectID;
232
+ incidentId: ObjectID;
233
+ }): Promise<Array<LinkedAffectedResource>> {
234
+ return await LinkedAffectedResources.readForIncidents({
235
+ service: data.service,
236
+ projectId: data.projectId,
237
+ incidentIds: [data.incidentId],
238
+ });
239
+ }
240
+
241
+ public static async readForIncidents(data: {
242
+ service: LinkedAffectedResourceReader<Incident>;
243
+ projectId: ObjectID;
244
+ incidentIds: Array<ObjectID>;
245
+ }): Promise<Array<LinkedAffectedResource>> {
246
+ return await LinkedAffectedResources.read({
247
+ service: data.service,
248
+ model: new Incident(),
249
+ projectId: data.projectId,
250
+ recordIds: data.incidentIds,
251
+ });
252
+ }
253
+
254
+ public static async readForAlert(data: {
255
+ service: LinkedAffectedResourceReader<Alert>;
256
+ projectId: ObjectID;
257
+ alertId: ObjectID;
258
+ }): Promise<Array<LinkedAffectedResource>> {
259
+ return await LinkedAffectedResources.readForAlerts({
260
+ service: data.service,
261
+ projectId: data.projectId,
262
+ alertIds: [data.alertId],
263
+ });
264
+ }
265
+
266
+ public static async readForAlerts(data: {
267
+ service: LinkedAffectedResourceReader<Alert>;
268
+ projectId: ObjectID;
269
+ alertIds: Array<ObjectID>;
270
+ }): Promise<Array<LinkedAffectedResource>> {
271
+ return await LinkedAffectedResources.read({
272
+ service: data.service,
273
+ model: new Alert(),
274
+ projectId: data.projectId,
275
+ recordIds: data.alertIds,
276
+ });
277
+ }
278
+
279
+ public static async readForScheduledMaintenance(data: {
280
+ service: LinkedAffectedResourceReader<ScheduledMaintenance>;
281
+ projectId: ObjectID;
282
+ scheduledMaintenanceId: ObjectID;
283
+ }): Promise<Array<LinkedAffectedResource>> {
284
+ return await LinkedAffectedResources.read({
285
+ service: data.service,
286
+ model: new ScheduledMaintenance(),
287
+ projectId: data.projectId,
288
+ recordIds: [data.scheduledMaintenanceId],
289
+ });
290
+ }
291
+
292
+ /*
293
+ * The resources linked to any of `recordIds`, merged into one list.
294
+ *
295
+ * One query per relation rather than one query selecting them all: the
296
+ * relations are many-to-many, and joining a dozen of them at once returns
297
+ * the product of their sizes - an incident on 50 monitors and 50 hosts
298
+ * would come back as 2,500 rows. Read one at a time, the rows add up.
299
+ */
300
+ private static async read<TBaseModel extends DatabaseBaseModel>(data: {
301
+ service: LinkedAffectedResourceReader<TBaseModel>;
302
+ model: TBaseModel;
303
+ projectId: ObjectID;
304
+ recordIds: Array<ObjectID>;
305
+ }): Promise<Array<LinkedAffectedResource>> {
306
+ const recordIds: Array<ObjectID> = [];
307
+ const seenRecordIds: Set<string> = new Set<string>();
308
+
309
+ for (const recordId of data.recordIds) {
310
+ const key: string = recordId?.toString() || "";
311
+
312
+ if (!key || seenRecordIds.has(key)) {
313
+ continue;
314
+ }
315
+
316
+ seenRecordIds.add(key);
317
+ recordIds.push(recordId);
318
+ }
319
+
320
+ if (recordIds.length === 0) {
321
+ return [];
322
+ }
323
+
324
+ const rowsPerRelation: Array<Array<TBaseModel> | undefined> =
325
+ await Promise.all(
326
+ LinkedAffectedResources.getRelations(data.model).map(
327
+ (
328
+ relation: LinkedAffectedResourceRelation,
329
+ ): Promise<Array<TBaseModel>> => {
330
+ return data.service.findAllBy({
331
+ query: {
332
+ _id: QueryHelper.any(recordIds),
333
+ projectId: data.projectId,
334
+ } as unknown as Query<TBaseModel>,
335
+ select: {
336
+ _id: true,
337
+ projectId: true,
338
+ [relation.column]: {
339
+ _id: true,
340
+ name: true,
341
+ projectId: true,
342
+ },
343
+ } as unknown as Select<TBaseModel>,
344
+ props: {
345
+ isRoot: true,
346
+ },
347
+ });
348
+ },
349
+ ),
350
+ );
351
+
352
+ return LinkedAffectedResources.collect({
353
+ projectId: data.projectId,
354
+ records: rowsPerRelation.flatMap(
355
+ (rows: Array<TBaseModel> | undefined): Array<TBaseModel> => {
356
+ return rows || [];
357
+ },
358
+ ) as unknown as Array<RecordWithRelations>,
359
+ });
360
+ }
361
+
362
+ /*
363
+ * The resources on already-read records, in display order and without
364
+ * repeats. A related row is kept only when it has an id and belongs to
365
+ * `projectId`; a row whose project was not read cannot be shown to belong
366
+ * here, so it is left out too - which also makes a caller that drops
367
+ * projectId from its select fail loudly in tests rather than quietly
368
+ * print nothing.
369
+ */
370
+ public static collect(data: {
371
+ projectId: ObjectID;
372
+ records: Array<RecordWithRelations | null | undefined>;
373
+ }): Array<LinkedAffectedResource> {
374
+ const resources: Array<LinkedAffectedResource> = [];
375
+ const seen: Set<string> = new Set<string>();
376
+
377
+ const records: Array<RecordWithRelations> = data.records.filter(
378
+ (record: RecordWithRelations | null | undefined): boolean => {
379
+ if (!record) {
380
+ return false;
381
+ }
382
+
383
+ // A record read without its project is taken to be the caller's.
384
+ return (
385
+ !record.projectId || isSameProject(record.projectId, data.projectId)
386
+ );
387
+ },
388
+ ) as Array<RecordWithRelations>;
389
+
390
+ for (const relation of LINKED_AFFECTED_RESOURCE_RELATIONS) {
391
+ for (const record of records) {
392
+ const value: unknown = record[relation.column];
393
+
394
+ const rows: Array<RelatedRow | null | undefined> = Array.isArray(value)
395
+ ? (value as Array<RelatedRow | null | undefined>)
396
+ : value
397
+ ? [value as RelatedRow]
398
+ : [];
399
+
400
+ for (const row of rows) {
401
+ const id: string = row?._id?.toString() || "";
402
+
403
+ if (!row || !id || !isSameProject(row.projectId, data.projectId)) {
404
+ continue;
405
+ }
406
+
407
+ const key: string = `${relation.type}:${id}`;
408
+
409
+ if (seen.has(key)) {
410
+ continue;
411
+ }
412
+
413
+ seen.add(key);
414
+
415
+ resources.push({
416
+ type: relation.type,
417
+ id: id,
418
+ name: row.name?.toString() || "",
419
+ });
420
+ }
421
+ }
422
+ }
423
+
424
+ return resources;
425
+ }
426
+
427
+ /*
428
+ * The names, for plain-text surfaces: emails and workspace summaries.
429
+ *
430
+ * `seriesSummary` is an alert's series identity - the pod or container a
431
+ * grouped monitor raised it for (SeriesLabelDisplay.buildInlineSummary).
432
+ * It names what broke more precisely than the monitor does, so it takes
433
+ * the monitor's place at the head of the list rather than joining it.
434
+ *
435
+ * A name that repeats (a monitor and a host both called "web-01") is
436
+ * printed once: this is a sentence, not a table.
437
+ */
438
+ public static getNames(data: {
439
+ resources: Array<LinkedAffectedResource>;
440
+ seriesSummary?: string | undefined;
441
+ }): Array<string> {
442
+ const names: Array<string> = [];
443
+ const seenNames: Set<string> = new Set<string>();
444
+ const seriesSummary: string = data.seriesSummary?.trim() || "";
445
+
446
+ const addName: (name: string) => void = (name: string): void => {
447
+ const trimmed: string = name.trim();
448
+
449
+ if (!trimmed || seenNames.has(trimmed)) {
450
+ return;
451
+ }
452
+
453
+ seenNames.add(trimmed);
454
+ names.push(trimmed);
455
+ };
456
+
457
+ addName(seriesSummary);
458
+
459
+ for (const resource of data.resources) {
460
+ if (
461
+ seriesSummary &&
462
+ resource.type === LinkedAffectedResourceType.Monitor
463
+ ) {
464
+ continue;
465
+ }
466
+
467
+ addName(resource.name);
468
+ }
469
+
470
+ return names;
471
+ }
472
+
473
+ // getNames joined with ", ", or `fallback` when there are none.
474
+ public static getText(data: {
475
+ resources: Array<LinkedAffectedResource>;
476
+ seriesSummary?: string | undefined;
477
+ fallback: string;
478
+ }): string {
479
+ return (
480
+ LinkedAffectedResources.getNames({
481
+ resources: data.resources,
482
+ seriesSummary: data.seriesSummary,
483
+ }).join(", ") || data.fallback
484
+ );
485
+ }
486
+
487
+ public static getDashboardUrl(data: {
488
+ dashboardUrl: URL;
489
+ projectId: ObjectID;
490
+ resource: LinkedAffectedResource;
491
+ }): URL {
492
+ const relation: LinkedAffectedResourceRelation =
493
+ LinkedAffectedResources.getRelationForType(data.resource.type);
494
+
495
+ // URL.addRoute mutates, and the caller reuses its dashboard URL.
496
+ return URL.fromString(data.dashboardUrl.toString()).addRoute(
497
+ `/${data.projectId.toString()}/${relation.dashboardRoute}/${data.resource.id}`,
498
+ );
499
+ }
500
+
501
+ /*
502
+ * The bullets under a feed item's "🌎 Resources Affected" header.
503
+ *
504
+ * A monitor keeps the bullet the created feeds have always printed,
505
+ * `- [<name>](<monitor link>)`, and an SLO keeps `- [SLO <name>](<link>)`
506
+ * from getSloAffectedResourceMarkdownLines. Every other resource follows
507
+ * the SLO's shape, `- [Host <name>](<link>)`, so the reader can tell a host
508
+ * from a cluster from a service.
509
+ *
510
+ * Those names are escaped: feeds render without safe mode and the same
511
+ * markdown goes to Slack and Teams, and a host or cluster name can come
512
+ * from an agent rather than from someone typing it.
513
+ */
514
+ public static getMarkdownLines(data: {
515
+ dashboardUrl: URL;
516
+ projectId: ObjectID;
517
+ resources: Array<LinkedAffectedResource>;
518
+ }): Array<string> {
519
+ const lines: Array<string> = [];
520
+ const slos: Array<SloAffectedResourceLinkSubject> = [];
521
+
522
+ for (const resource of data.resources) {
523
+ if (resource.type === LinkedAffectedResourceType.ServiceLevelObjective) {
524
+ slos.push({
525
+ _id: resource.id,
526
+ name: resource.name,
527
+ // Already held to this project by collect.
528
+ projectId: data.projectId,
529
+ });
530
+ continue;
531
+ }
532
+
533
+ const link: string = LinkedAffectedResources.getDashboardUrl({
534
+ dashboardUrl: data.dashboardUrl,
535
+ projectId: data.projectId,
536
+ resource: resource,
537
+ }).toString();
538
+
539
+ if (resource.type === LinkedAffectedResourceType.Monitor) {
540
+ lines.push(`- [${resource.name}](${link})`);
541
+ continue;
542
+ }
543
+
544
+ const label: string = LinkedAffectedResources.getRelationForType(
545
+ resource.type,
546
+ ).label;
547
+ const escapedName: string = escapeMarkdownInline(resource.name).trim();
548
+
549
+ lines.push(
550
+ `- [${escapedName ? `${label} ${escapedName}` : label}](${link})`,
551
+ );
552
+ }
553
+
554
+ // SLOs are last in the table, so appending them keeps the order.
555
+ lines.push(
556
+ ...getSloAffectedResourceMarkdownLines({
557
+ dashboardUrl: data.dashboardUrl,
558
+ projectId: data.projectId,
559
+ serviceLevelObjectives: slos,
560
+ }),
561
+ );
562
+
563
+ return lines;
564
+ }
565
+
566
+ private static getRelationForType(
567
+ type: LinkedAffectedResourceType,
568
+ ): LinkedAffectedResourceRelation {
569
+ // Every type has at least one entry, so this always finds one.
570
+ return LINKED_AFFECTED_RESOURCE_RELATIONS.find(
571
+ (relation: LinkedAffectedResourceRelation) => {
572
+ return relation.type === type;
573
+ },
574
+ )!;
575
+ }
576
+ }