@oneuptime/common 12.0.2 → 12.0.3

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 (228) hide show
  1. package/Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel.ts +14 -0
  2. package/Models/DatabaseModels/Index.ts +2 -0
  3. package/Models/DatabaseModels/LogDropFilter.ts +9 -20
  4. package/Models/DatabaseModels/StatusPageMonitorRule.ts +911 -0
  5. package/Models/DatabaseModels/StatusPageResource.ts +73 -0
  6. package/Models/DatabaseModels/TraceDropFilter.ts +9 -20
  7. package/Server/API/BaseAPI.ts +13 -2
  8. package/Server/API/DashboardAPI.ts +39 -0
  9. package/Server/EnvironmentConfig.ts +31 -1
  10. package/Server/Infrastructure/GlobalCache.ts +115 -0
  11. package/Server/Infrastructure/Postgres/DataSourceOptions.ts +16 -0
  12. package/Server/Infrastructure/Postgres/SchemaMigrations/1786005052769-AddStatusPageMonitorRule.ts +123 -0
  13. package/Server/Infrastructure/Postgres/SchemaMigrations/Index.ts +2 -0
  14. package/Server/Services/AlertStateTimelineService.ts +20 -0
  15. package/Server/Services/CephClusterService.ts +26 -86
  16. package/Server/Services/CloudResourceService.ts +23 -83
  17. package/Server/Services/DatabaseService.ts +111 -0
  18. package/Server/Services/DockerHostService.ts +19 -79
  19. package/Server/Services/DockerSwarmClusterService.ts +27 -88
  20. package/Server/Services/HostService.ts +46 -99
  21. package/Server/Services/IncidentStateTimelineService.ts +20 -0
  22. package/Server/Services/Index.ts +2 -0
  23. package/Server/Services/IoTFleetService.ts +19 -79
  24. package/Server/Services/KubernetesClusterService.ts +17 -78
  25. package/Server/Services/LabelService.ts +57 -10
  26. package/Server/Services/MetricTypeService.ts +84 -0
  27. package/Server/Services/MonitorService.ts +89 -14
  28. package/Server/Services/MonitorStatusTimelineService.ts +29 -0
  29. package/Server/Services/MonitorTemplateService.ts +65 -0
  30. package/Server/Services/PodmanHostService.ts +19 -79
  31. package/Server/Services/ProxmoxClusterService.ts +23 -83
  32. package/Server/Services/RumApplicationService.ts +19 -80
  33. package/Server/Services/ScheduledMaintenanceStateTimelineService.ts +21 -0
  34. package/Server/Services/ServerlessFunctionService.ts +24 -85
  35. package/Server/Services/ServiceService.ts +299 -73
  36. package/Server/Services/StatusPageMonitorRuleEngineService.ts +752 -0
  37. package/Server/Services/StatusPageMonitorRuleService.ts +471 -0
  38. package/Server/Services/TelemetryEntityRelationshipService.ts +1 -0
  39. package/Server/Services/TelemetryEntityService.ts +1 -0
  40. package/Server/Utils/Database/ProjectScopedReferenceValidator.ts +170 -39
  41. package/Server/Utils/Monitor/MonitorResource.ts +63 -36
  42. package/Server/Utils/Monitor/MonitorStatusTimeline.ts +36 -0
  43. package/Server/Utils/Monitor/MonitorStepsProjectValidator.ts +148 -127
  44. package/Server/Utils/Monitor/MonitorStepsReferenceExtractor.ts +434 -0
  45. package/Server/Utils/SingleFlight.ts +83 -0
  46. package/Server/Utils/StatusPage/MonitorRulePatternValidator.ts +46 -0
  47. package/Server/Utils/Telemetry/EntityRegistry.ts +107 -26
  48. package/Server/Utils/Telemetry/ResourceHeartbeat.ts +314 -0
  49. package/Server/Utils/Telemetry/Telemetry.ts +351 -122
  50. package/Tests/App/Dashboard/WidgetCatalog.test.ts +2 -0
  51. package/Tests/Models/DatabaseModels/ColumnTransformerInvariants.test.ts +306 -0
  52. package/Tests/Models/DatabaseModels/NumberColumnDeserialization.test.ts +333 -0
  53. package/Tests/Models/DatabaseModels/StatusPageMonitorRuleModel.test.ts +190 -0
  54. package/Tests/Server/API/DashboardPublicResourceListAPI.test.ts +26 -0
  55. package/Tests/Server/Infrastructure/GlobalCache.test.ts +226 -0
  56. package/Tests/Server/Infrastructure/PostgresLockTimeoutOptions.test.ts +181 -0
  57. package/Tests/Server/Services/DatabaseServiceUpdateColumnsIfUnlocked.test.ts +342 -0
  58. package/Tests/Server/Services/DropFilterSaveValidation.test.ts +245 -0
  59. package/Tests/Server/Services/HostServiceUpdateLastSeen.test.ts +163 -15
  60. package/Tests/Server/Services/MetricTypeAttachServices.test.ts +222 -0
  61. package/Tests/Server/Services/MissingReferenceWriteGuard.test.ts +614 -0
  62. package/Tests/Server/Services/MonitorStatusTimelineFastPath.test.ts +23 -0
  63. package/Tests/Server/Services/ResourceUpdateLastSeenLivenessFallback.test.ts +305 -56
  64. package/Tests/Server/Services/ServiceUpdateLastSeenSplitGates.test.ts +705 -0
  65. package/Tests/Server/Services/StatusPageMonitorRuleEngineService.test.ts +1719 -0
  66. package/Tests/Server/Services/StatusPageMonitorRuleHooks.test.ts +1212 -0
  67. package/Tests/Server/Services/StatusPageMonitorRuleMonitorCreateHook.test.ts +228 -0
  68. package/Tests/Server/Utils/APIKey/AccessPermission.test.ts +267 -0
  69. package/Tests/Server/Utils/Database/ProjectScopedReferenceValidator.test.ts +260 -13
  70. package/Tests/Server/Utils/EntityRegistryRowFence.test.ts +302 -0
  71. package/Tests/Server/Utils/MetricTypeIndexConvergence.test.ts +598 -0
  72. package/Tests/Server/Utils/Monitor/MonitorStatusTimelineUnusableStatus.test.ts +154 -0
  73. package/Tests/Server/Utils/Monitor/MonitorStepsProjectValidator.test.ts +638 -92
  74. package/Tests/Server/Utils/Monitor/MonitorStepsReferenceExtractor.test.ts +724 -0
  75. package/Tests/Server/Utils/SingleFlight.test.ts +221 -0
  76. package/Tests/Types/Dashboard/NetworkDashboardTemplate.test.ts +793 -0
  77. package/Tests/Types/Database/BigIntColumnTransformer.test.ts +147 -0
  78. package/Tests/Types/Database/DatabasePropertyTransformer.test.ts +140 -0
  79. package/Tests/Types/Database/NumericColumnValue.test.ts +127 -0
  80. package/Tests/Types/Decimal.test.ts +37 -0
  81. package/Tests/Types/Monitor/SnmpVersionParsing.test.ts +152 -0
  82. package/Tests/Types/Port.test.ts +38 -0
  83. package/Tests/UI/Components/LogsHistogram.test.tsx +276 -0
  84. package/Tests/UI/Components/UseLiveLogsRefresh.test.tsx +489 -0
  85. package/Tests/UI/Components/UseLogsHistogram.test.tsx +500 -0
  86. package/Tests/Utils/Dashboard/Components/DashboardComponentsUtil.test.ts +120 -0
  87. package/Tests/Utils/Dashboard/DashboardNetworkMapComponent.test.ts +327 -0
  88. package/Types/Dashboard/DashboardComponentType.ts +1 -0
  89. package/Types/Dashboard/DashboardComponents/ComponentArgument.ts +1 -0
  90. package/Types/Dashboard/DashboardComponents/DashboardNetworkMapComponent.ts +40 -0
  91. package/Types/Dashboard/DashboardTemplates.ts +397 -0
  92. package/Types/Database/BigIntColumnTransformer.ts +74 -0
  93. package/Types/Database/DatabaseProperty.ts +26 -0
  94. package/Types/Database/NumericColumnValue.ts +128 -0
  95. package/Types/Decimal.ts +16 -4
  96. package/Types/Permission.ts +48 -0
  97. package/Types/Port.ts +16 -4
  98. package/UI/Components/LogsViewer/useLiveLogsRefresh.ts +86 -0
  99. package/UI/Components/LogsViewer/useLogsHistogram.ts +113 -0
  100. package/Utils/Dashboard/Components/DashboardNetworkMapComponent.ts +136 -0
  101. package/Utils/Dashboard/Components/Index.ts +7 -0
  102. package/build/dist/Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel.js +12 -0
  103. package/build/dist/Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel.js.map +1 -1
  104. package/build/dist/Models/DatabaseModels/Index.js +2 -0
  105. package/build/dist/Models/DatabaseModels/Index.js.map +1 -1
  106. package/build/dist/Models/DatabaseModels/LogDropFilter.js +9 -20
  107. package/build/dist/Models/DatabaseModels/LogDropFilter.js.map +1 -1
  108. package/build/dist/Models/DatabaseModels/StatusPageMonitorRule.js +925 -0
  109. package/build/dist/Models/DatabaseModels/StatusPageMonitorRule.js.map +1 -0
  110. package/build/dist/Models/DatabaseModels/StatusPageResource.js +72 -0
  111. package/build/dist/Models/DatabaseModels/StatusPageResource.js.map +1 -1
  112. package/build/dist/Models/DatabaseModels/TraceDropFilter.js +9 -20
  113. package/build/dist/Models/DatabaseModels/TraceDropFilter.js.map +1 -1
  114. package/build/dist/Server/API/BaseAPI.js +11 -1
  115. package/build/dist/Server/API/BaseAPI.js.map +1 -1
  116. package/build/dist/Server/API/DashboardAPI.js +39 -0
  117. package/build/dist/Server/API/DashboardAPI.js.map +1 -1
  118. package/build/dist/Server/EnvironmentConfig.js +27 -1
  119. package/build/dist/Server/EnvironmentConfig.js.map +1 -1
  120. package/build/dist/Server/Infrastructure/GlobalCache.js +91 -0
  121. package/build/dist/Server/Infrastructure/GlobalCache.js.map +1 -1
  122. package/build/dist/Server/Infrastructure/Postgres/DataSourceOptions.js +5 -3
  123. package/build/dist/Server/Infrastructure/Postgres/DataSourceOptions.js.map +1 -1
  124. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1786005052769-AddStatusPageMonitorRule.js +48 -0
  125. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1786005052769-AddStatusPageMonitorRule.js.map +1 -0
  126. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js +2 -0
  127. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js.map +1 -1
  128. package/build/dist/Server/Services/AlertStateTimelineService.js +19 -0
  129. package/build/dist/Server/Services/AlertStateTimelineService.js.map +1 -1
  130. package/build/dist/Server/Services/CephClusterService.js +26 -76
  131. package/build/dist/Server/Services/CephClusterService.js.map +1 -1
  132. package/build/dist/Server/Services/CloudResourceService.js +23 -73
  133. package/build/dist/Server/Services/CloudResourceService.js.map +1 -1
  134. package/build/dist/Server/Services/DatabaseService.js +86 -0
  135. package/build/dist/Server/Services/DatabaseService.js.map +1 -1
  136. package/build/dist/Server/Services/DockerHostService.js +19 -69
  137. package/build/dist/Server/Services/DockerHostService.js.map +1 -1
  138. package/build/dist/Server/Services/DockerSwarmClusterService.js +27 -78
  139. package/build/dist/Server/Services/DockerSwarmClusterService.js.map +1 -1
  140. package/build/dist/Server/Services/HostService.js +58 -102
  141. package/build/dist/Server/Services/HostService.js.map +1 -1
  142. package/build/dist/Server/Services/IncidentStateTimelineService.js +19 -0
  143. package/build/dist/Server/Services/IncidentStateTimelineService.js.map +1 -1
  144. package/build/dist/Server/Services/Index.js +2 -0
  145. package/build/dist/Server/Services/Index.js.map +1 -1
  146. package/build/dist/Server/Services/IoTFleetService.js +19 -69
  147. package/build/dist/Server/Services/IoTFleetService.js.map +1 -1
  148. package/build/dist/Server/Services/KubernetesClusterService.js +17 -68
  149. package/build/dist/Server/Services/KubernetesClusterService.js.map +1 -1
  150. package/build/dist/Server/Services/LabelService.js +42 -7
  151. package/build/dist/Server/Services/LabelService.js.map +1 -1
  152. package/build/dist/Server/Services/MetricTypeService.js +74 -0
  153. package/build/dist/Server/Services/MetricTypeService.js.map +1 -1
  154. package/build/dist/Server/Services/MonitorService.js +81 -9
  155. package/build/dist/Server/Services/MonitorService.js.map +1 -1
  156. package/build/dist/Server/Services/MonitorStatusTimelineService.js +28 -0
  157. package/build/dist/Server/Services/MonitorStatusTimelineService.js.map +1 -1
  158. package/build/dist/Server/Services/MonitorTemplateService.js +60 -0
  159. package/build/dist/Server/Services/MonitorTemplateService.js.map +1 -1
  160. package/build/dist/Server/Services/PodmanHostService.js +19 -69
  161. package/build/dist/Server/Services/PodmanHostService.js.map +1 -1
  162. package/build/dist/Server/Services/ProxmoxClusterService.js +23 -73
  163. package/build/dist/Server/Services/ProxmoxClusterService.js.map +1 -1
  164. package/build/dist/Server/Services/RumApplicationService.js +19 -70
  165. package/build/dist/Server/Services/RumApplicationService.js.map +1 -1
  166. package/build/dist/Server/Services/ScheduledMaintenanceStateTimelineService.js +20 -0
  167. package/build/dist/Server/Services/ScheduledMaintenanceStateTimelineService.js.map +1 -1
  168. package/build/dist/Server/Services/ServerlessFunctionService.js +24 -75
  169. package/build/dist/Server/Services/ServerlessFunctionService.js.map +1 -1
  170. package/build/dist/Server/Services/ServiceService.js +236 -61
  171. package/build/dist/Server/Services/ServiceService.js.map +1 -1
  172. package/build/dist/Server/Services/StatusPageMonitorRuleEngineService.js +603 -0
  173. package/build/dist/Server/Services/StatusPageMonitorRuleEngineService.js.map +1 -0
  174. package/build/dist/Server/Services/StatusPageMonitorRuleService.js +401 -0
  175. package/build/dist/Server/Services/StatusPageMonitorRuleService.js.map +1 -0
  176. package/build/dist/Server/Services/TelemetryEntityRelationshipService.js +1 -0
  177. package/build/dist/Server/Services/TelemetryEntityRelationshipService.js.map +1 -1
  178. package/build/dist/Server/Services/TelemetryEntityService.js +1 -0
  179. package/build/dist/Server/Services/TelemetryEntityService.js.map +1 -1
  180. package/build/dist/Server/Utils/Database/ProjectScopedReferenceValidator.js +105 -29
  181. package/build/dist/Server/Utils/Database/ProjectScopedReferenceValidator.js.map +1 -1
  182. package/build/dist/Server/Utils/Monitor/MonitorResource.js +56 -32
  183. package/build/dist/Server/Utils/Monitor/MonitorResource.js.map +1 -1
  184. package/build/dist/Server/Utils/Monitor/MonitorStatusTimeline.js +30 -3
  185. package/build/dist/Server/Utils/Monitor/MonitorStatusTimeline.js.map +1 -1
  186. package/build/dist/Server/Utils/Monitor/MonitorStepsProjectValidator.js +110 -98
  187. package/build/dist/Server/Utils/Monitor/MonitorStepsProjectValidator.js.map +1 -1
  188. package/build/dist/Server/Utils/Monitor/MonitorStepsReferenceExtractor.js +312 -0
  189. package/build/dist/Server/Utils/Monitor/MonitorStepsReferenceExtractor.js.map +1 -0
  190. package/build/dist/Server/Utils/SingleFlight.js +76 -0
  191. package/build/dist/Server/Utils/SingleFlight.js.map +1 -0
  192. package/build/dist/Server/Utils/StatusPage/MonitorRulePatternValidator.js +29 -0
  193. package/build/dist/Server/Utils/StatusPage/MonitorRulePatternValidator.js.map +1 -0
  194. package/build/dist/Server/Utils/Telemetry/EntityRegistry.js +78 -19
  195. package/build/dist/Server/Utils/Telemetry/EntityRegistry.js.map +1 -1
  196. package/build/dist/Server/Utils/Telemetry/ResourceHeartbeat.js +160 -0
  197. package/build/dist/Server/Utils/Telemetry/ResourceHeartbeat.js.map +1 -0
  198. package/build/dist/Server/Utils/Telemetry/Telemetry.js +279 -104
  199. package/build/dist/Server/Utils/Telemetry/Telemetry.js.map +1 -1
  200. package/build/dist/Types/Dashboard/DashboardComponentType.js +1 -0
  201. package/build/dist/Types/Dashboard/DashboardComponentType.js.map +1 -1
  202. package/build/dist/Types/Dashboard/DashboardComponents/ComponentArgument.js +1 -0
  203. package/build/dist/Types/Dashboard/DashboardComponents/ComponentArgument.js.map +1 -1
  204. package/build/dist/Types/Dashboard/DashboardComponents/DashboardNetworkMapComponent.js +2 -0
  205. package/build/dist/Types/Dashboard/DashboardComponents/DashboardNetworkMapComponent.js.map +1 -0
  206. package/build/dist/Types/Dashboard/DashboardTemplates.js +368 -0
  207. package/build/dist/Types/Dashboard/DashboardTemplates.js.map +1 -1
  208. package/build/dist/Types/Database/BigIntColumnTransformer.js +66 -0
  209. package/build/dist/Types/Database/BigIntColumnTransformer.js.map +1 -0
  210. package/build/dist/Types/Database/DatabaseProperty.js +25 -0
  211. package/build/dist/Types/Database/DatabaseProperty.js.map +1 -1
  212. package/build/dist/Types/Database/NumericColumnValue.js +97 -0
  213. package/build/dist/Types/Database/NumericColumnValue.js.map +1 -0
  214. package/build/dist/Types/Decimal.js +14 -3
  215. package/build/dist/Types/Decimal.js.map +1 -1
  216. package/build/dist/Types/Permission.js +42 -0
  217. package/build/dist/Types/Permission.js.map +1 -1
  218. package/build/dist/Types/Port.js +15 -5
  219. package/build/dist/Types/Port.js.map +1 -1
  220. package/build/dist/UI/Components/LogsViewer/useLiveLogsRefresh.js +44 -0
  221. package/build/dist/UI/Components/LogsViewer/useLiveLogsRefresh.js.map +1 -0
  222. package/build/dist/UI/Components/LogsViewer/useLogsHistogram.js +75 -0
  223. package/build/dist/UI/Components/LogsViewer/useLogsHistogram.js.map +1 -0
  224. package/build/dist/Utils/Dashboard/Components/DashboardNetworkMapComponent.js +114 -0
  225. package/build/dist/Utils/Dashboard/Components/DashboardNetworkMapComponent.js.map +1 -0
  226. package/build/dist/Utils/Dashboard/Components/Index.js +4 -0
  227. package/build/dist/Utils/Dashboard/Components/Index.js.map +1 -1
  228. package/package.json +1 -1
@@ -0,0 +1,434 @@
1
+ import { JSONArray, JSONObject, JSONValue } from "../../../Types/JSON";
2
+ import MonitorSteps from "../../../Types/Monitor/MonitorSteps";
3
+ import ObjectID from "../../../Types/ObjectID";
4
+ import Typeof from "../../../Types/Typeof";
5
+
6
+ /*
7
+ * `monitorSteps` is a free-form JSON column, so none of the ids it embeds have
8
+ * a foreign key behind them. They are still real references: the monitor status
9
+ * a criteria switches to, the severity it opens incidents and alerts with, the
10
+ * on-call policies it pages, the labels/owners it stamps on what it creates.
11
+ *
12
+ * Until issue #3039 the only guard over this blob scraped every uuid out of the
13
+ * serialized JSON with a regex and asked whether it happened to be another
14
+ * project's record. That can never reject an id that exists nowhere, because
15
+ * monitorSteps is FULL of uuids that are not references at all — step ids,
16
+ * criteria ids, incident/alert template ids — and they match nothing either.
17
+ *
18
+ * This walker exists to tell those apart. It reads the structure rather than the
19
+ * text, so every id it yields is known to be a reference to a specific model and
20
+ * can be checked for existence without any risk of a false rejection.
21
+ */
22
+
23
+ export enum MonitorStepsReferenceModel {
24
+ MonitorStatus = "Monitor Status",
25
+ IncidentSeverity = "Incident Severity",
26
+ AlertSeverity = "Alert Severity",
27
+ OnCallDutyPolicy = "On-Call Duty Policy",
28
+ Label = "Label",
29
+ Team = "Team",
30
+ User = "User",
31
+ IncidentRole = "Incident Role",
32
+ TelemetryService = "Telemetry Service",
33
+ NetworkDevice = "Network Device",
34
+ }
35
+
36
+ /*
37
+ * Step-level sub-configs that scope a monitor to specific telemetry services.
38
+ * All five carry the field under the same name.
39
+ */
40
+ const TELEMETRY_SERVICE_STEP_FIELDS: Array<string> = [
41
+ "logMonitor",
42
+ "traceMonitor",
43
+ "exceptionMonitor",
44
+ "profileMonitor",
45
+ "metricMonitor",
46
+ ];
47
+
48
+ export interface MonitorStepsReference {
49
+ model: MonitorStepsReferenceModel;
50
+ id: string;
51
+ /*
52
+ * Human readable location inside monitorSteps, used verbatim in the error
53
+ * message so a caller can find the offending field without diffing JSON.
54
+ * e.g. `criteria "Monitor is offline" incident severity`.
55
+ */
56
+ path: string;
57
+ /*
58
+ * Whether the monitor actually uses this id when it runs.
59
+ *
60
+ * A criteria carries `monitorStatusId` even when `changeMonitorStatus` is
61
+ * off, and carries whole incident/alert templates even when `createIncidents`
62
+ * / `createAlerts` are off — the UI keeps them so toggling the switch back on
63
+ * restores what you had. Only the operative ones can produce the foreign key
64
+ * violation in issue #3039, and only those are required to exist; requiring
65
+ * the rest would refuse a save over a field that does nothing, and would lock
66
+ * a user out of a monitor whose disabled criteria points at something they
67
+ * have since deleted.
68
+ *
69
+ * Cross-project checking does not use this flag — every reference is checked
70
+ * for that, operative or not, exactly as before.
71
+ */
72
+ isOperative: boolean;
73
+ }
74
+
75
+ /*
76
+ * Every level of monitorSteps is persisted inside a `{ _type, value }` envelope
77
+ * (MonitorSteps.toJSON -> MonitorStep.toJSON -> MonitorCriteria.toJSON ->
78
+ * MonitorCriteriaInstance.toJSON). API callers - Terraform among them - post
79
+ * the same envelope. Unwrap it when it is there and accept the bare object when
80
+ * it is not, so a hand-written payload is walked just as thoroughly.
81
+ */
82
+ function unwrap(value: JSONValue | undefined): JSONObject | null {
83
+ if (!value || typeof value !== Typeof.Object || Array.isArray(value)) {
84
+ return null;
85
+ }
86
+
87
+ const object: JSONObject = value as JSONObject;
88
+
89
+ if (object["value"] && typeof object["value"] === Typeof.Object) {
90
+ return object["value"] as JSONObject;
91
+ }
92
+
93
+ return object;
94
+ }
95
+
96
+ function asArray(value: JSONValue | undefined): JSONArray {
97
+ return Array.isArray(value) ? (value as JSONArray) : [];
98
+ }
99
+
100
+ /*
101
+ * An id reaches here in every shape the codebase produces: a plain uuid string
102
+ * (MonitorSteps.toJSON stringifies defaultMonitorStatusId and monitorStatusId),
103
+ * a serialized `{ _type: "ObjectID", value }` envelope (what JSONFunctions.serialize
104
+ * does to the ObjectIDs nested inside the incidents/alerts arrays), a live
105
+ * ObjectID instance (validating a MonitorSteps object that was never
106
+ * serialized), or `{ value }` without the marker.
107
+ *
108
+ * Blank is treated as absent on purpose: a stored `{"_type":"ObjectID","value":""}`
109
+ * rehydrates to `new ObjectID("")`, which is truthy. Reporting that as a missing
110
+ * *reference* would be misleading - it is an unset field, and the required-field
111
+ * checks own that case.
112
+ */
113
+ export function toReferenceId(value: JSONValue | undefined): string | null {
114
+ if (!value) {
115
+ return null;
116
+ }
117
+
118
+ if (value instanceof ObjectID) {
119
+ return value.toString().trim() || null;
120
+ }
121
+
122
+ if (typeof value === Typeof.String) {
123
+ return (value as string).trim() || null;
124
+ }
125
+
126
+ if (typeof value === Typeof.Object && !Array.isArray(value)) {
127
+ const inner: JSONValue | undefined = (value as JSONObject)["value"];
128
+
129
+ if (typeof inner === Typeof.String) {
130
+ return (inner as string).trim() || null;
131
+ }
132
+ }
133
+
134
+ return null;
135
+ }
136
+
137
+ export default class MonitorStepsReferenceExtractor {
138
+ /*
139
+ * Walks monitorSteps and returns every id it holds that points at another
140
+ * record. Ids that are NOT references (step ids, criteria ids, the id on each
141
+ * incident/alert template) are deliberately not returned - they are local
142
+ * identity, not a pointer to a row.
143
+ */
144
+ public static extract(
145
+ monitorSteps: MonitorSteps | JSONObject | undefined | null,
146
+ ): Array<MonitorStepsReference> {
147
+ const root: JSONObject | null = this.toJSONObject(monitorSteps);
148
+
149
+ if (!root) {
150
+ return [];
151
+ }
152
+
153
+ const references: Array<MonitorStepsReference> = [];
154
+
155
+ this.push(references, {
156
+ model: MonitorStepsReferenceModel.MonitorStatus,
157
+ value: root["defaultMonitorStatusId"],
158
+ path: "default monitor status",
159
+ /*
160
+ * Always operative: MonitorResource stamps it onto the monitor's first
161
+ * MonitorStatusTimeline row, which is the very insert issue #3039 reports
162
+ * failing.
163
+ */
164
+ isOperative: true,
165
+ });
166
+
167
+ const steps: JSONArray = asArray(root["monitorStepsInstanceArray"]);
168
+
169
+ for (const step of steps) {
170
+ const stepValue: JSONObject | null = unwrap(step as JSONValue);
171
+
172
+ if (!stepValue) {
173
+ continue;
174
+ }
175
+
176
+ this.extractFromStepConfig(references, stepValue);
177
+
178
+ const criteria: JSONObject | null = unwrap(stepValue["monitorCriteria"]);
179
+
180
+ if (!criteria) {
181
+ continue;
182
+ }
183
+
184
+ const instances: JSONArray = asArray(
185
+ criteria["monitorCriteriaInstanceArray"],
186
+ );
187
+
188
+ for (let index: number = 0; index < instances.length; index++) {
189
+ this.extractFromCriteriaInstance({
190
+ references: references,
191
+ criteriaInstance: unwrap(instances[index] as JSONValue),
192
+ index: index,
193
+ });
194
+ }
195
+ }
196
+
197
+ return references;
198
+ }
199
+
200
+ /*
201
+ * The step's own targets: the telemetry services a log/trace/exception/
202
+ * profile/metric monitor is scoped to, and the device a network monitor
203
+ * walks.
204
+ *
205
+ * These are reported as references — so a *cross-project* id in them is
206
+ * refused like any other — but never as `isOperative`, so they are not
207
+ * required to exist. Both already degrade on their own when the target is
208
+ * gone (the query simply matches nothing; NetworkDeviceHydrationUtil logs a
209
+ * warning and carries on), neither can produce the foreign key violation this
210
+ * guard exists for, and deleting a telemetry service is ordinary enough that
211
+ * refusing every later edit of a monitor that once watched it would be a
212
+ * worse failure than the one being fixed.
213
+ */
214
+ private static extractFromStepConfig(
215
+ references: Array<MonitorStepsReference>,
216
+ step: JSONObject,
217
+ ): void {
218
+ for (const field of TELEMETRY_SERVICE_STEP_FIELDS) {
219
+ const config: JSONObject | null = unwrap(step[field]);
220
+
221
+ if (!config) {
222
+ continue;
223
+ }
224
+
225
+ for (const id of asArray(config["telemetryServiceIds"])) {
226
+ this.push(references, {
227
+ model: MonitorStepsReferenceModel.TelemetryService,
228
+ value: id as JSONValue,
229
+ path: "monitored telemetry service",
230
+ isOperative: false,
231
+ });
232
+ }
233
+ }
234
+
235
+ const networkDeviceMonitor: JSONObject | null = unwrap(
236
+ step["networkDeviceMonitor"],
237
+ );
238
+
239
+ if (networkDeviceMonitor) {
240
+ this.push(references, {
241
+ model: MonitorStepsReferenceModel.NetworkDevice,
242
+ value: networkDeviceMonitor["networkDeviceId"],
243
+ path: "monitored network device",
244
+ isOperative: false,
245
+ });
246
+ }
247
+ }
248
+
249
+ private static extractFromCriteriaInstance(data: {
250
+ references: Array<MonitorStepsReference>;
251
+ criteriaInstance: JSONObject | null;
252
+ index: number;
253
+ }): void {
254
+ const criteriaInstance: JSONObject | null = data.criteriaInstance;
255
+
256
+ if (!criteriaInstance) {
257
+ return;
258
+ }
259
+
260
+ const name: string =
261
+ (criteriaInstance["name"] as string) || `#${data.index + 1}`;
262
+ const label: string = `criteria "${name}"`;
263
+
264
+ this.push(data.references, {
265
+ model: MonitorStepsReferenceModel.MonitorStatus,
266
+ value: criteriaInstance["monitorStatusId"],
267
+ path: `${label} monitor status`,
268
+ isOperative: criteriaInstance["changeMonitorStatus"] === true,
269
+ });
270
+
271
+ const createsIncidents: boolean =
272
+ criteriaInstance["createIncidents"] === true;
273
+
274
+ for (const incident of asArray(criteriaInstance["incidents"])) {
275
+ const incidentValue: JSONObject | null = unwrap(incident as JSONValue);
276
+
277
+ if (!incidentValue) {
278
+ continue;
279
+ }
280
+
281
+ this.push(data.references, {
282
+ model: MonitorStepsReferenceModel.IncidentSeverity,
283
+ value: incidentValue["incidentSeverityId"],
284
+ path: `${label} incident severity`,
285
+ isOperative: createsIncidents,
286
+ });
287
+
288
+ this.pushSharedNotificationReferences({
289
+ references: data.references,
290
+ source: incidentValue,
291
+ label: `${label} incident`,
292
+ isOperative: createsIncidents,
293
+ });
294
+
295
+ for (const roleAssignment of asArray(
296
+ incidentValue["incidentMemberRoles"],
297
+ )) {
298
+ const assignment: JSONObject | null = unwrap(
299
+ roleAssignment as JSONValue,
300
+ );
301
+
302
+ if (!assignment) {
303
+ continue;
304
+ }
305
+
306
+ this.push(data.references, {
307
+ model: MonitorStepsReferenceModel.IncidentRole,
308
+ value: assignment["roleId"],
309
+ path: `${label} incident member role`,
310
+ isOperative: createsIncidents,
311
+ });
312
+
313
+ this.push(data.references, {
314
+ model: MonitorStepsReferenceModel.User,
315
+ value: assignment["userId"],
316
+ path: `${label} incident member`,
317
+ isOperative: createsIncidents,
318
+ });
319
+ }
320
+ }
321
+
322
+ const createsAlerts: boolean = criteriaInstance["createAlerts"] === true;
323
+
324
+ for (const alert of asArray(criteriaInstance["alerts"])) {
325
+ const alertValue: JSONObject | null = unwrap(alert as JSONValue);
326
+
327
+ if (!alertValue) {
328
+ continue;
329
+ }
330
+
331
+ this.push(data.references, {
332
+ model: MonitorStepsReferenceModel.AlertSeverity,
333
+ value: alertValue["alertSeverityId"],
334
+ path: `${label} alert severity`,
335
+ isOperative: createsAlerts,
336
+ });
337
+
338
+ this.pushSharedNotificationReferences({
339
+ references: data.references,
340
+ source: alertValue,
341
+ label: `${label} alert`,
342
+ isOperative: createsAlerts,
343
+ });
344
+ }
345
+ }
346
+
347
+ // The four id arrays CriteriaIncident and CriteriaAlert have in common.
348
+ private static pushSharedNotificationReferences(data: {
349
+ references: Array<MonitorStepsReference>;
350
+ source: JSONObject;
351
+ label: string;
352
+ isOperative: boolean;
353
+ }): void {
354
+ const arrays: Array<{
355
+ field: string;
356
+ model: MonitorStepsReferenceModel;
357
+ path: string;
358
+ }> = [
359
+ {
360
+ field: "onCallPolicyIds",
361
+ model: MonitorStepsReferenceModel.OnCallDutyPolicy,
362
+ path: "on-call policy",
363
+ },
364
+ {
365
+ field: "labelIds",
366
+ model: MonitorStepsReferenceModel.Label,
367
+ path: "label",
368
+ },
369
+ {
370
+ field: "ownerTeamIds",
371
+ model: MonitorStepsReferenceModel.Team,
372
+ path: "owner team",
373
+ },
374
+ {
375
+ field: "ownerUserIds",
376
+ model: MonitorStepsReferenceModel.User,
377
+ path: "owner user",
378
+ },
379
+ ];
380
+
381
+ for (const array of arrays) {
382
+ for (const id of asArray(data.source[array.field])) {
383
+ this.push(data.references, {
384
+ model: array.model,
385
+ value: id as JSONValue,
386
+ path: `${data.label} ${array.path}`,
387
+ isOperative: data.isOperative,
388
+ });
389
+ }
390
+ }
391
+ }
392
+
393
+ private static push(
394
+ references: Array<MonitorStepsReference>,
395
+ data: {
396
+ model: MonitorStepsReferenceModel;
397
+ value: JSONValue | undefined;
398
+ path: string;
399
+ isOperative: boolean;
400
+ },
401
+ ): void {
402
+ const id: string | null = toReferenceId(data.value);
403
+
404
+ if (!id) {
405
+ return;
406
+ }
407
+
408
+ references.push({
409
+ model: data.model,
410
+ id: id,
411
+ path: data.path,
412
+ isOperative: data.isOperative,
413
+ });
414
+ }
415
+
416
+ private static toJSONObject(
417
+ monitorSteps: MonitorSteps | JSONObject | undefined | null,
418
+ ): JSONObject | null {
419
+ if (!monitorSteps) {
420
+ return null;
421
+ }
422
+
423
+ if (monitorSteps instanceof MonitorSteps) {
424
+ /*
425
+ * toJSON() on a MonitorSteps whose `data` is undefined returns the
426
+ * "new monitor steps" skeleton, which holds no references. Walking it is
427
+ * harmless.
428
+ */
429
+ return unwrap(monitorSteps.toJSON());
430
+ }
431
+
432
+ return unwrap(monitorSteps);
433
+ }
434
+ }
@@ -0,0 +1,83 @@
1
+ /*
2
+ * In-process de-duplication of concurrent identical work.
3
+ *
4
+ * A Redis fence admits one writer per window across the FLEET, but every
5
+ * caller still pays a Redis round trip to discover it lost. That is the wrong
6
+ * unit of work when the duplicate callers are in the same process: an ingest
7
+ * pod running hundreds of concurrent jobs re-resolves the same handful of
8
+ * services on every batch, so hundreds of coroutines independently ask Redis
9
+ * the same question and then throw the answer away.
10
+ *
11
+ * SingleFlight collapses them first. The first caller for a key runs the work;
12
+ * everyone who arrives while it is still in flight awaits the SAME promise and
13
+ * gets the same result. Per pod, N concurrent duplicates cost one Redis round
14
+ * trip and at most one database write instead of N of each — which is what
15
+ * turns fleet-wide write amplification from (pods x jobs) into (pods).
16
+ *
17
+ * Deliberately unbounded in time but not in size: entries live only for the
18
+ * duration of the work itself and are removed in a `finally`, so the map holds
19
+ * exactly the set of operations currently running. There is no eviction policy
20
+ * to get wrong and nothing to leak if work hangs beyond a caller's patience —
21
+ * the entry is released when the underlying promise settles either way.
22
+ *
23
+ * This is a per-process optimisation and NOT a correctness mechanism: nothing
24
+ * here coordinates across pods. It composes with a distributed fence, it does
25
+ * not replace one.
26
+ */
27
+ export default class SingleFlight {
28
+ private static inflight: Map<string, Promise<unknown>> = new Map<
29
+ string,
30
+ Promise<unknown>
31
+ >();
32
+
33
+ /**
34
+ * Run `work` for `key`, or join the run already in flight for it.
35
+ *
36
+ * Followers observe whatever the leader observes, including a rejection.
37
+ * That is intentional: these callers asked for identical work, so they are
38
+ * entitled to identical outcomes, and a follower silently retrying a failure
39
+ * the leader just hit would re-create the stampede this exists to prevent.
40
+ */
41
+ public static async run<T>(key: string, work: () => Promise<T>): Promise<T> {
42
+ const existing: Promise<unknown> | undefined = this.inflight.get(key);
43
+
44
+ if (existing) {
45
+ return (await existing) as T;
46
+ }
47
+
48
+ /*
49
+ * Invoke through a wrapper so a `work` that throws SYNCHRONOUSLY still
50
+ * produces a promise to register and await. Calling it bare would throw
51
+ * past the bookkeeping below and leave the key registered forever.
52
+ */
53
+ const promise: Promise<T> = (async () => {
54
+ return await work();
55
+ })();
56
+
57
+ this.inflight.set(key, promise);
58
+
59
+ try {
60
+ return await promise;
61
+ } finally {
62
+ /*
63
+ * Only clear the entry if it is still ours. A follower cannot install a
64
+ * new one (it awaited instead), but a later leader can, and blindly
65
+ * deleting here would evict that live run and let the next caller start
66
+ * a duplicate of work already underway.
67
+ */
68
+ if (this.inflight.get(key) === promise) {
69
+ this.inflight.delete(key);
70
+ }
71
+ }
72
+ }
73
+
74
+ /** Number of operations currently in flight. For tests and diagnostics. */
75
+ public static inflightCount(): number {
76
+ return this.inflight.size;
77
+ }
78
+
79
+ /** Drop all bookkeeping. For tests only. */
80
+ public static clear(): void {
81
+ this.inflight.clear();
82
+ }
83
+ }
@@ -0,0 +1,46 @@
1
+ import BadDataException from "../../../Types/Exception/BadDataException";
2
+ import RulePatternMatchUtil from "../../../Utils/Rules/RulePatternMatchUtil";
3
+
4
+ /*
5
+ * Write-time validation for the monitor name / description patterns on status
6
+ * page monitor rules.
7
+ *
8
+ * The rule engine accepts a case-insensitive regex or a '*' wildcard glob, the
9
+ * same two syntaxes the network device rules take. Anything else - `api-(01`,
10
+ * `[unclosed` - compiles to nothing and matches nothing, and the engine can
11
+ * only log about it long after the user left the form. Reject it at the write
12
+ * instead, exactly as NetworkDeviceRulePatternValidator does
13
+ * (OneUptime/oneuptime#2940).
14
+ */
15
+ export default class StatusPageMonitorRulePatternValidator {
16
+ public static validate(data: {
17
+ namePattern?: string | null | undefined;
18
+ descriptionPattern?: string | null | undefined;
19
+ }): void {
20
+ StatusPageMonitorRulePatternValidator.validateOne(
21
+ "Monitor Name Pattern",
22
+ data.namePattern,
23
+ );
24
+ StatusPageMonitorRulePatternValidator.validateOne(
25
+ "Monitor Description Pattern",
26
+ data.descriptionPattern,
27
+ );
28
+ }
29
+
30
+ private static validateOne(
31
+ title: string,
32
+ pattern: string | null | undefined,
33
+ ): void {
34
+ if (!pattern) {
35
+ return;
36
+ }
37
+
38
+ if (RulePatternMatchUtil.isSupportedPattern(pattern)) {
39
+ return;
40
+ }
41
+
42
+ throw new BadDataException(
43
+ `${title} "${pattern}" is not a valid regular expression, and contains no '*' wildcard to fall back on, so it would never match a monitor. Use a regex such as api-.* or a wildcard such as *api*.`,
44
+ );
45
+ }
46
+ }