Skip to main content

mz_audit_log/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Audit log data structures.
11//!
12//! The audit log is logging that is produced by user actions and consumed
13//! by users in the form of the `mz_catalog.mz_audit_events` SQL table and
14//! by the cloud management layer for billing and introspection. This crate
15//! is designed to make the production and consumption of the logs type
16//! safe. Events and their metadata are versioned and the data structures
17//! replicated here so that if the data change in some other crate, a
18//! new version here can be made. This avoids needing to poke at the data
19//! when reading it to determine what it means and should have full backward
20//! compatibility. This is its own crate so that production and consumption can
21//! be in different processes and production is not allowed to specify private
22//! data structures unknown to the reader.
23//!
24//! `EventDetails::as_json` produces the JSON that
25//! `mz_catalog.mz_audit_events.details` exposes. The durable catalog stores
26//! the proto twin from `mz_catalog_protos::objects::audit_log_event_v1`,
27//! which `parse_catalog_audit_log_details` (in
28//! `src/catalog-decode/src/audit_log.rs`) reshapes back into
29//! `as_json`'s output. Changes here that shift that output (new variants,
30//! renamed fields, added `skip_serializing_if`, field-name diffs against
31//! the proto) need matching updates there. The round-trip is covered by
32//! the property test in `src/catalog/tests/audit_log_details.rs`.
33
34use std::time::Duration;
35
36use mz_ore::now::EpochMillis;
37use proptest_derive::Arbitrary;
38use serde::{Deserialize, Serialize};
39
40/// New version variants should be added if fields need to be added, changed, or removed.
41#[derive(
42    Clone,
43    Debug,
44    Serialize,
45    Deserialize,
46    PartialOrd,
47    PartialEq,
48    Eq,
49    Ord,
50    Hash,
51    Arbitrary
52)]
53pub enum VersionedEvent {
54    V1(EventV1),
55}
56
57impl VersionedEvent {
58    /// Create a new event. This function must always require and produce the most
59    /// recent variant of VersionedEvent. `id` must be a globally increasing,
60    /// ordered number such that sorting by it on all events yields the order
61    /// of events by users. It is insufficient to use `occurred_at` (even at
62    /// nanosecond precision) due to clock unpredictability.
63    pub fn new(
64        id: u64,
65        event_type: EventType,
66        object_type: ObjectType,
67        details: EventDetails,
68        user: Option<String>,
69        occurred_at: EpochMillis,
70    ) -> Self {
71        Self::V1(EventV1::new(
72            id,
73            event_type,
74            object_type,
75            details,
76            user,
77            occurred_at,
78        ))
79    }
80
81    // Implement deserialize and serialize so writers and readers don't have to
82    // coordinate about which Serializer to use.
83    pub fn deserialize(data: &[u8]) -> Result<Self, anyhow::Error> {
84        Ok(serde_json::from_slice(data)?)
85    }
86
87    pub fn serialize(&self) -> Vec<u8> {
88        serde_json::to_vec(self).expect("must serialize")
89    }
90
91    /// Returns a globally sortable event order. All event versions must have this
92    /// field.
93    pub fn sortable_id(&self) -> u64 {
94        match self {
95            VersionedEvent::V1(ev) => ev.id,
96        }
97    }
98}
99
100#[derive(
101    Clone,
102    Debug,
103    Serialize,
104    Deserialize,
105    PartialOrd,
106    PartialEq,
107    Eq,
108    Ord,
109    Hash,
110    Arbitrary
111)]
112#[serde(rename_all = "kebab-case")]
113pub enum EventType {
114    Create,
115    Drop,
116    Alter,
117    Grant,
118    Revoke,
119    Comment,
120}
121
122impl EventType {
123    pub fn as_title_case(&self) -> &'static str {
124        match self {
125            EventType::Create => "Created",
126            EventType::Drop => "Dropped",
127            EventType::Alter => "Altered",
128            EventType::Grant => "Granted",
129            EventType::Revoke => "Revoked",
130            EventType::Comment => "Comment",
131        }
132    }
133}
134
135serde_plain::derive_display_from_serialize!(EventType);
136
137#[derive(
138    Clone,
139    Copy,
140    Debug,
141    Serialize,
142    Deserialize,
143    PartialOrd,
144    PartialEq,
145    Eq,
146    Ord,
147    Hash,
148    Arbitrary
149)]
150#[serde(rename_all = "kebab-case")]
151pub enum ObjectType {
152    Cluster,
153    ClusterReplica,
154    Connection,
155    ContinualTask,
156    Database,
157    Func,
158    Index,
159    MaterializedView,
160    MetricSink,
161    NetworkPolicy,
162    QueryPolicy,
163    Role,
164    Secret,
165    Schema,
166    Sink,
167    Source,
168    System,
169    Table,
170    Type,
171    View,
172}
173
174impl ObjectType {
175    pub fn as_title_case(&self) -> &'static str {
176        match self {
177            ObjectType::Cluster => "Cluster",
178            ObjectType::ClusterReplica => "Cluster Replica",
179            ObjectType::Connection => "Connection",
180            ObjectType::ContinualTask => "Continual Task",
181            ObjectType::Database => "Database",
182            ObjectType::Func => "Function",
183            ObjectType::Index => "Index",
184            ObjectType::MaterializedView => "Materialized View",
185            ObjectType::MetricSink => "Metric Sink",
186            ObjectType::NetworkPolicy => "Network Policy",
187            ObjectType::QueryPolicy => "Query Policy",
188            ObjectType::Role => "Role",
189            ObjectType::Schema => "Schema",
190            ObjectType::Secret => "Secret",
191            ObjectType::Sink => "Sink",
192            ObjectType::Source => "Source",
193            ObjectType::System => "System",
194            ObjectType::Table => "Table",
195            ObjectType::Type => "Type",
196            ObjectType::View => "View",
197        }
198    }
199}
200
201serde_plain::derive_display_from_serialize!(ObjectType);
202
203#[derive(
204    Clone,
205    Debug,
206    Serialize,
207    Deserialize,
208    PartialOrd,
209    PartialEq,
210    Eq,
211    Ord,
212    Hash,
213    Arbitrary
214)]
215pub enum EventDetails {
216    #[serde(rename = "CreateComputeReplicaV1")] // historical name
217    CreateClusterReplicaV1(CreateClusterReplicaV1),
218    CreateClusterReplicaV2(CreateClusterReplicaV2),
219    CreateClusterReplicaV3(CreateClusterReplicaV3),
220    CreateClusterReplicaV4(CreateClusterReplicaV4),
221    #[serde(rename = "DropComputeReplicaV1")] // historical name
222    DropClusterReplicaV1(DropClusterReplicaV1),
223    DropClusterReplicaV2(DropClusterReplicaV2),
224    DropClusterReplicaV3(DropClusterReplicaV3),
225    CreateSourceSinkV1(CreateSourceSinkV1),
226    CreateSourceSinkV2(CreateSourceSinkV2),
227    CreateSourceSinkV3(CreateSourceSinkV3),
228    CreateSourceSinkV4(CreateSourceSinkV4),
229    CreateIndexV1(CreateIndexV1),
230    CreateMaterializedViewV1(CreateMaterializedViewV1),
231    AlterApplyReplacementV1(AlterApplyReplacementV1),
232    AlterSetClusterV1(AlterSetClusterV1),
233    AlterSourceSinkV1(AlterSourceSinkV1),
234    GrantRoleV1(GrantRoleV1),
235    GrantRoleV2(GrantRoleV2),
236    RevokeRoleV1(RevokeRoleV1),
237    RevokeRoleV2(RevokeRoleV2),
238    UpdatePrivilegeV1(UpdatePrivilegeV1),
239    AlterDefaultPrivilegeV1(AlterDefaultPrivilegeV1),
240    UpdateOwnerV1(UpdateOwnerV1),
241    IdFullNameV1(IdFullNameV1),
242    RenameClusterV1(RenameClusterV1),
243    RenameClusterReplicaV1(RenameClusterReplicaV1),
244    AlterClusterReconfigurationV1(AlterClusterReconfigurationV1),
245    ClusterHydrationBurstV1(ClusterHydrationBurstV1),
246    RenameItemV1(RenameItemV1),
247    IdNameV1(IdNameV1),
248    SchemaV1(SchemaV1),
249    SchemaV2(SchemaV2),
250    UpdateItemV1(UpdateItemV1),
251    RenameSchemaV1(RenameSchemaV1),
252    AlterRetainHistoryV1(AlterRetainHistoryV1),
253    AlterAddColumnV1(AlterAddColumnV1),
254    AlterSourceTimestampIntervalV1(AlterSourceTimestampIntervalV1),
255    ToNewIdV1(ToNewIdV1),
256    FromPreviousIdV1(FromPreviousIdV1),
257    SetV1(SetV1),
258    ResetAllV1,
259    RotateKeysV1(RotateKeysV1),
260    CreateRoleV1(CreateRoleV1),
261}
262
263#[derive(
264    Clone,
265    Debug,
266    Serialize,
267    Deserialize,
268    PartialOrd,
269    PartialEq,
270    Eq,
271    Ord,
272    Hash,
273    Arbitrary
274)]
275pub struct SetV1 {
276    pub name: String,
277    pub value: Option<String>,
278}
279
280#[derive(
281    Clone,
282    Debug,
283    Serialize,
284    Deserialize,
285    PartialOrd,
286    PartialEq,
287    Eq,
288    Ord,
289    Hash,
290    Arbitrary
291)]
292pub struct RotateKeysV1 {
293    pub id: String,
294    pub name: String,
295}
296
297#[derive(
298    Clone,
299    Debug,
300    Serialize,
301    Deserialize,
302    PartialOrd,
303    PartialEq,
304    Eq,
305    Ord,
306    Hash,
307    Arbitrary
308)]
309pub struct IdFullNameV1 {
310    pub id: String,
311    #[serde(flatten)]
312    pub name: FullNameV1,
313}
314
315#[derive(
316    Clone,
317    Debug,
318    Serialize,
319    Deserialize,
320    PartialOrd,
321    PartialEq,
322    Eq,
323    Ord,
324    Hash,
325    Arbitrary
326)]
327pub struct FullNameV1 {
328    pub database: String,
329    pub schema: String,
330    pub item: String,
331}
332
333#[derive(
334    Clone,
335    Debug,
336    Serialize,
337    Deserialize,
338    PartialOrd,
339    PartialEq,
340    Eq,
341    Ord,
342    Hash,
343    Arbitrary
344)]
345pub struct IdNameV1 {
346    pub id: String,
347    pub name: String,
348}
349
350/// A transition in the lifecycle of a background cluster reconfiguration (a
351/// `reconfiguration` record on a managed cluster), recorded so an operator can
352/// trace a background `ALTER CLUSTER` from start to its resolution.
353///
354/// The replica creates and drops the reconfiguration induces are recorded
355/// separately, carrying [`CreateOrDropClusterReplicaReasonV1::Reconfiguration`];
356/// this event family records the cluster-level transitions those replica
357/// lifecycle events hang off of.
358#[derive(
359    Clone,
360    Debug,
361    Serialize,
362    Deserialize,
363    PartialOrd,
364    PartialEq,
365    Eq,
366    Ord,
367    Hash,
368    Arbitrary
369)]
370#[serde(rename_all = "kebab-case")]
371pub enum ReconfigurationLifecycleV1 {
372    /// A reconfiguration record was written or re-targeted: the cluster is now
373    /// converging onto a new target shape.
374    Started,
375    /// The realized config cut over to the target and the record was marked
376    /// finalized: a hydrated success under either `ON TIMEOUT` action
377    /// (including one that hydrated after the deadline, since success takes
378    /// precedence) or a forced `ON TIMEOUT COMMIT` cut-over of a
379    /// not-yet-hydrated target past the deadline. Which of the two it was is
380    /// recorded in [`AlterClusterReconfigurationV1::forced`].
381    Finalized,
382    /// The deadline fired with the target not hydrated under `ON TIMEOUT
383    /// ROLLBACK`: the record was marked timed out with the realized config
384    /// untouched and the target replicas dropped, reverting to the
385    /// pre-reconfiguration set. Emitted exactly once per timeout. The status
386    /// transition is durable, so it cannot re-fire. This event is the timeout's
387    /// papertrail, alongside the retained record.
388    TimedOut,
389    /// An in-flight reconfiguration was cancelled by re-targeting the record
390    /// back to the cluster's still-realized shape (the ALTER-back cancel path);
391    /// the controller drops the in-flight target replicas.
392    Cancelled,
393    /// The controller could not create the target replicas within the resource
394    /// budget and aborted the reconfiguration: the record was marked resource
395    /// exhausted with the realized config untouched, reverting to the
396    /// pre-reconfiguration set (like a rollback, but triggered by the budget
397    /// rather than the deadline). The status transition is durable, so it
398    /// cannot re-fire.
399    ResourceExhausted,
400}
401
402/// A cluster-level transition in a background reconfiguration's lifecycle.
403///
404/// `deadline` is the reconfiguration's active deadline as a millisecond
405/// `mz_timestamp`, recorded on every transition so an operator can correlate
406/// the transition with the originating `ALTER`.
407#[derive(
408    Clone,
409    Debug,
410    Serialize,
411    Deserialize,
412    PartialOrd,
413    PartialEq,
414    Eq,
415    Ord,
416    Hash,
417    Arbitrary
418)]
419pub struct AlterClusterReconfigurationV1 {
420    pub cluster_id: String,
421    pub cluster_name: String,
422    pub transition: ReconfigurationLifecycleV1,
423    /// On a `finalized` transition: whether the cut-over was forced by `ON
424    /// TIMEOUT COMMIT` at the deadline rather than reached by hydration.
425    /// `None` on every other transition.
426    #[serde(default)]
427    pub forced: Option<bool>,
428    pub target_size: String,
429    pub target_replication_factor: u32,
430    pub target_availability_zones: Vec<String>,
431    pub target_logging: ClusterReplicaLoggingV1,
432    pub deadline: Option<u64>,
433}
434
435/// A managed cluster's introspection-logging config, recorded on a
436/// reconfiguration event so the papertrail captures an introspection-only
437/// `ALTER` (which otherwise leaves `target_size` and
438/// `target_replication_factor` unchanged from the realized shape). Mirrors the
439/// durable `ReplicaLogging`: `log_logging` is `INTROSPECTION DEBUGGING`,
440/// `interval` is `INTROSPECTION INTERVAL` (`None` disables introspection).
441#[derive(
442    Clone,
443    Debug,
444    Serialize,
445    Deserialize,
446    PartialOrd,
447    PartialEq,
448    Eq,
449    Ord,
450    Hash,
451    Arbitrary
452)]
453pub struct ClusterReplicaLoggingV1 {
454    pub log_logging: bool,
455    pub interval: Option<Duration>,
456}
457
458#[derive(
459    Clone,
460    Debug,
461    Serialize,
462    Deserialize,
463    PartialOrd,
464    PartialEq,
465    Eq,
466    Ord,
467    Hash,
468    Arbitrary
469)]
470pub struct CreateRoleV1 {
471    pub id: String,
472    pub name: String,
473    pub auto_provision_source: Option<String>,
474}
475
476/// A transition in the lifecycle of a hydration burst (a `burst` record on a
477/// managed cluster), recorded so an operator can trace a controller-initiated
478/// burst from start to teardown.
479///
480/// The burst replica's create and drop are recorded separately, carrying
481/// [`CreateOrDropClusterReplicaReasonV1::HydrationBurst`]; this event family
482/// records the cluster-level transitions those replica lifecycle events hang off.
483#[derive(
484    Clone,
485    Debug,
486    Serialize,
487    Deserialize,
488    PartialOrd,
489    PartialEq,
490    Eq,
491    Ord,
492    Hash,
493    Arbitrary
494)]
495#[serde(rename_all = "kebab-case")]
496pub enum HydrationBurstLifecycleV1 {
497    /// A `burst` record was written: the controller is now running a burst
498    /// replica to accelerate hydration.
499    Started,
500    /// The `burst` record was cleared: the burst replica is torn down. Why is
501    /// recorded in [`ClusterHydrationBurstV1::finish_cause`].
502    Finished,
503}
504
505/// Why a hydration burst finished, recorded on a `finished` transition.
506#[derive(
507    Clone,
508    Copy,
509    Debug,
510    Serialize,
511    Deserialize,
512    PartialOrd,
513    PartialEq,
514    Eq,
515    Ord,
516    Hash,
517    Arbitrary
518)]
519#[serde(rename_all = "kebab-case")]
520pub enum BurstFinishCauseV1 {
521    /// The steady replica set hydrated and the linger duration elapsed.
522    LingerElapsed,
523    /// The burst is no longer warranted by current config: the auto-scaling
524    /// policy was removed or its hydration size changed, the cluster was
525    /// turned off, or burst was disabled environment-wide.
526    NoLongerWarranted,
527}
528
529/// A cluster-level transition in a hydration burst's lifecycle.
530#[derive(
531    Clone,
532    Debug,
533    Serialize,
534    Deserialize,
535    PartialOrd,
536    PartialEq,
537    Eq,
538    Ord,
539    Hash,
540    Arbitrary
541)]
542pub struct ClusterHydrationBurstV1 {
543    pub cluster_id: String,
544    pub cluster_name: String,
545    pub transition: HydrationBurstLifecycleV1,
546    /// On a `finished` transition: why the burst tore down. `None` on `started`.
547    #[serde(default)]
548    pub finish_cause: Option<BurstFinishCauseV1>,
549    /// The size of the burst replica the record runs.
550    pub burst_size: String,
551}
552
553#[derive(
554    Clone,
555    Debug,
556    Serialize,
557    Deserialize,
558    PartialOrd,
559    PartialEq,
560    Eq,
561    Ord,
562    Hash,
563    Arbitrary
564)]
565pub struct RenameItemV1 {
566    pub id: String,
567    pub old_name: FullNameV1,
568    pub new_name: FullNameV1,
569}
570
571#[derive(
572    Clone,
573    Debug,
574    Serialize,
575    Deserialize,
576    PartialOrd,
577    PartialEq,
578    Eq,
579    Ord,
580    Hash,
581    Arbitrary
582)]
583pub struct RenameClusterV1 {
584    pub id: String,
585    pub old_name: String,
586    pub new_name: String,
587}
588
589#[derive(
590    Clone,
591    Debug,
592    Serialize,
593    Deserialize,
594    PartialOrd,
595    PartialEq,
596    Eq,
597    Ord,
598    Hash,
599    Arbitrary
600)]
601pub struct RenameClusterReplicaV1 {
602    pub cluster_id: String,
603    pub replica_id: String,
604    pub old_name: String,
605    pub new_name: String,
606}
607
608#[derive(
609    Clone,
610    Debug,
611    Serialize,
612    Deserialize,
613    PartialOrd,
614    PartialEq,
615    Eq,
616    Ord,
617    Hash,
618    Arbitrary
619)]
620pub struct DropClusterReplicaV1 {
621    pub cluster_id: String,
622    pub cluster_name: String,
623    // Events that predate v0.32.0 will not have this field set.
624    #[serde(skip_serializing_if = "Option::is_none")]
625    pub replica_id: Option<String>,
626    pub replica_name: String,
627}
628
629#[derive(
630    Clone,
631    Debug,
632    Serialize,
633    Deserialize,
634    PartialOrd,
635    PartialEq,
636    Eq,
637    Ord,
638    Hash,
639    Arbitrary
640)]
641pub struct DropClusterReplicaV2 {
642    pub cluster_id: String,
643    pub cluster_name: String,
644    pub replica_id: Option<String>,
645    pub replica_name: String,
646    pub reason: CreateOrDropClusterReplicaReasonV1,
647    #[serde(skip_serializing_if = "Option::is_none")]
648    pub scheduling_policies: Option<SchedulingDecisionsWithReasonsV1>,
649}
650
651#[derive(
652    Clone,
653    Debug,
654    Serialize,
655    Deserialize,
656    PartialOrd,
657    PartialEq,
658    Eq,
659    Ord,
660    Hash,
661    Arbitrary
662)]
663pub struct DropClusterReplicaV3 {
664    pub cluster_id: String,
665    pub cluster_name: String,
666    pub replica_id: Option<String>,
667    pub replica_name: String,
668    pub reason: CreateOrDropClusterReplicaReasonV1,
669    #[serde(skip_serializing_if = "Option::is_none")]
670    pub scheduling_policies: Option<SchedulingDecisionsWithReasonsV2>,
671}
672
673#[derive(
674    Clone,
675    Debug,
676    Serialize,
677    Deserialize,
678    PartialOrd,
679    PartialEq,
680    Eq,
681    Ord,
682    Hash,
683    Arbitrary
684)]
685pub struct CreateClusterReplicaV1 {
686    pub cluster_id: String,
687    pub cluster_name: String,
688    // Events that predate v0.32.0 will not have this field set.
689    #[serde(skip_serializing_if = "Option::is_none")]
690    pub replica_id: Option<String>,
691    pub replica_name: String,
692    pub logical_size: String,
693    pub disk: bool,
694    pub billed_as: Option<String>,
695    pub internal: bool,
696}
697
698#[derive(
699    Clone,
700    Debug,
701    Serialize,
702    Deserialize,
703    PartialOrd,
704    PartialEq,
705    Eq,
706    Ord,
707    Hash,
708    Arbitrary
709)]
710pub struct CreateClusterReplicaV2 {
711    pub cluster_id: String,
712    pub cluster_name: String,
713    pub replica_id: Option<String>,
714    pub replica_name: String,
715    pub logical_size: String,
716    pub disk: bool,
717    pub billed_as: Option<String>,
718    pub internal: bool,
719    pub reason: CreateOrDropClusterReplicaReasonV1,
720    #[serde(skip_serializing_if = "Option::is_none")]
721    pub scheduling_policies: Option<SchedulingDecisionsWithReasonsV1>,
722}
723
724#[derive(
725    Clone,
726    Debug,
727    Serialize,
728    Deserialize,
729    PartialOrd,
730    PartialEq,
731    Eq,
732    Ord,
733    Hash,
734    Arbitrary
735)]
736pub struct CreateClusterReplicaV3 {
737    pub cluster_id: String,
738    pub cluster_name: String,
739    pub replica_id: Option<String>,
740    pub replica_name: String,
741    pub logical_size: String,
742    pub disk: bool,
743    pub billed_as: Option<String>,
744    pub internal: bool,
745    pub reason: CreateOrDropClusterReplicaReasonV1,
746    #[serde(skip_serializing_if = "Option::is_none")]
747    pub scheduling_policies: Option<SchedulingDecisionsWithReasonsV2>,
748}
749
750#[derive(
751    Clone,
752    Debug,
753    Serialize,
754    Deserialize,
755    PartialOrd,
756    PartialEq,
757    Eq,
758    Ord,
759    Hash,
760    Arbitrary
761)]
762pub struct CreateClusterReplicaV4 {
763    pub cluster_id: String,
764    pub cluster_name: String,
765    pub replica_id: Option<String>,
766    pub replica_name: String,
767    pub logical_size: String,
768    pub billed_as: Option<String>,
769    pub internal: bool,
770    pub reason: CreateOrDropClusterReplicaReasonV1,
771    #[serde(skip_serializing_if = "Option::is_none")]
772    pub scheduling_policies: Option<SchedulingDecisionsWithReasonsV2>,
773}
774
775#[derive(
776    Clone,
777    Debug,
778    Serialize,
779    Deserialize,
780    PartialOrd,
781    PartialEq,
782    Eq,
783    Ord,
784    Hash,
785    Arbitrary
786)]
787#[serde(rename_all = "kebab-case")]
788pub enum CreateOrDropClusterReplicaReasonV1 {
789    Manual,
790    Schedule,
791    System,
792    /// The cluster controller's graceful-reconfiguration strategy created the
793    /// replica while converging a cluster onto an in-flight `reconfiguration`
794    /// target (a background `ALTER CLUSTER`).
795    Reconfiguration,
796    /// The cluster controller's hydration-burst strategy created the
797    /// transient burst replica it runs while a cluster's objects are not yet
798    /// hydrated.
799    HydrationBurst,
800    /// The cluster controller dropped the replica because the cluster's
801    /// configuration no longer calls for it. NOTE: a replication-factor
802    /// decrease drop reads `retired` even though the config change itself was
803    /// user-initiated.
804    Retired,
805}
806
807/// The reason for the automated cluster scheduling to turn a cluster On or Off. Each existing
808/// policy's On/Off opinion should be recorded, along with their reasons. (Among the reasons there
809/// can be settings of the policy as well as other information about the state of the system.)
810#[derive(
811    Clone,
812    Debug,
813    Serialize,
814    Deserialize,
815    PartialOrd,
816    PartialEq,
817    Eq,
818    Ord,
819    Hash,
820    Arbitrary
821)]
822pub struct SchedulingDecisionsWithReasonsV1 {
823    /// The reason for the refresh policy for wanting to turn a cluster On or Off.
824    pub on_refresh: RefreshDecisionWithReasonV1,
825}
826
827/// The reason for the automated cluster scheduling to turn a cluster On or Off. Each existing
828/// policy's On/Off opinion should be recorded, along with their reasons. (Among the reasons there
829/// can be settings of the policy as well as other information about the state of the system.)
830#[derive(
831    Clone,
832    Debug,
833    Serialize,
834    Deserialize,
835    PartialOrd,
836    PartialEq,
837    Eq,
838    Ord,
839    Hash,
840    Arbitrary
841)]
842pub struct SchedulingDecisionsWithReasonsV2 {
843    /// The reason for the refresh policy for wanting to turn a cluster On or Off.
844    pub on_refresh: RefreshDecisionWithReasonV2,
845}
846
847#[derive(
848    Clone,
849    Debug,
850    Serialize,
851    Deserialize,
852    PartialOrd,
853    PartialEq,
854    Eq,
855    Ord,
856    Hash,
857    Arbitrary
858)]
859pub struct RefreshDecisionWithReasonV1 {
860    pub decision: SchedulingDecisionV1,
861    /// Objects that currently need a refresh on the cluster (taking into account the rehydration
862    /// time estimate).
863    pub objects_needing_refresh: Vec<String>,
864    /// The HYDRATION TIME ESTIMATE setting of the cluster.
865    pub hydration_time_estimate: String,
866}
867
868#[derive(
869    Clone,
870    Debug,
871    Serialize,
872    Deserialize,
873    PartialOrd,
874    PartialEq,
875    Eq,
876    Ord,
877    Hash,
878    Arbitrary
879)]
880pub struct RefreshDecisionWithReasonV2 {
881    pub decision: SchedulingDecisionV1,
882    /// Objects that currently need a refresh on the cluster (taking into account the rehydration
883    /// time estimate), and therefore should keep the cluster On.
884    pub objects_needing_refresh: Vec<String>,
885    /// Objects for which we estimate that they currently need Persist compaction, and therefore
886    /// should keep the cluster On.
887    pub objects_needing_compaction: Vec<String>,
888    /// The HYDRATION TIME ESTIMATE setting of the cluster.
889    pub hydration_time_estimate: String,
890}
891
892#[derive(
893    Clone,
894    Debug,
895    Serialize,
896    Deserialize,
897    PartialOrd,
898    PartialEq,
899    Eq,
900    Ord,
901    Hash,
902    Arbitrary
903)]
904#[serde(rename_all = "kebab-case")]
905pub enum SchedulingDecisionV1 {
906    On,
907    Off,
908}
909
910impl From<bool> for SchedulingDecisionV1 {
911    fn from(value: bool) -> Self {
912        match value {
913            true => SchedulingDecisionV1::On,
914            false => SchedulingDecisionV1::Off,
915        }
916    }
917}
918
919#[derive(
920    Clone,
921    Debug,
922    Serialize,
923    Deserialize,
924    PartialOrd,
925    PartialEq,
926    Eq,
927    Ord,
928    Hash,
929    Arbitrary
930)]
931pub struct CreateSourceSinkV1 {
932    pub id: String,
933    #[serde(flatten)]
934    pub name: FullNameV1,
935    pub size: Option<String>,
936}
937
938#[derive(
939    Clone,
940    Debug,
941    Serialize,
942    Deserialize,
943    PartialOrd,
944    PartialEq,
945    Eq,
946    Ord,
947    Hash,
948    Arbitrary
949)]
950pub struct CreateSourceSinkV2 {
951    pub id: String,
952    #[serde(flatten)]
953    pub name: FullNameV1,
954    pub size: Option<String>,
955    #[serde(rename = "type")]
956    pub external_type: String,
957}
958
959#[derive(
960    Clone,
961    Debug,
962    Serialize,
963    Deserialize,
964    PartialOrd,
965    PartialEq,
966    Eq,
967    Ord,
968    Hash,
969    Arbitrary
970)]
971pub struct CreateSourceSinkV3 {
972    pub id: String,
973    #[serde(flatten)]
974    pub name: FullNameV1,
975    #[serde(rename = "type")]
976    pub external_type: String,
977}
978
979#[derive(
980    Clone,
981    Debug,
982    Serialize,
983    Deserialize,
984    PartialOrd,
985    PartialEq,
986    Eq,
987    Ord,
988    Hash,
989    Arbitrary
990)]
991pub struct CreateSourceSinkV4 {
992    pub id: String,
993    pub cluster_id: Option<String>,
994    #[serde(flatten)]
995    pub name: FullNameV1,
996    #[serde(rename = "type")]
997    pub external_type: String,
998}
999
1000#[derive(
1001    Clone,
1002    Debug,
1003    Serialize,
1004    Deserialize,
1005    PartialOrd,
1006    PartialEq,
1007    Eq,
1008    Ord,
1009    Hash,
1010    Arbitrary
1011)]
1012pub struct CreateIndexV1 {
1013    pub id: String,
1014    pub cluster_id: String,
1015    #[serde(flatten)]
1016    pub name: FullNameV1,
1017}
1018
1019#[derive(
1020    Clone,
1021    Debug,
1022    Serialize,
1023    Deserialize,
1024    PartialOrd,
1025    PartialEq,
1026    Eq,
1027    Ord,
1028    Hash,
1029    Arbitrary
1030)]
1031pub struct CreateMaterializedViewV1 {
1032    pub id: String,
1033    pub cluster_id: String,
1034    #[serde(flatten)]
1035    pub name: FullNameV1,
1036    #[serde(skip_serializing_if = "Option::is_none")]
1037    pub replacement_target_id: Option<String>,
1038}
1039
1040#[derive(
1041    Clone,
1042    Debug,
1043    Serialize,
1044    Deserialize,
1045    PartialOrd,
1046    PartialEq,
1047    Eq,
1048    Ord,
1049    Hash,
1050    Arbitrary
1051)]
1052pub struct AlterApplyReplacementV1 {
1053    #[serde(flatten)]
1054    pub target: IdFullNameV1,
1055    pub replacement: IdFullNameV1,
1056}
1057
1058#[derive(
1059    Clone,
1060    Debug,
1061    Serialize,
1062    Deserialize,
1063    PartialOrd,
1064    PartialEq,
1065    Eq,
1066    Ord,
1067    Hash,
1068    Arbitrary
1069)]
1070pub struct AlterSourceSinkV1 {
1071    pub id: String,
1072    #[serde(flatten)]
1073    pub name: FullNameV1,
1074    pub old_size: Option<String>,
1075    pub new_size: Option<String>,
1076}
1077
1078#[derive(
1079    Clone,
1080    Debug,
1081    Serialize,
1082    Deserialize,
1083    PartialOrd,
1084    PartialEq,
1085    Eq,
1086    Ord,
1087    Hash,
1088    Arbitrary
1089)]
1090pub struct AlterSetClusterV1 {
1091    pub id: String,
1092    #[serde(flatten)]
1093    pub name: FullNameV1,
1094    pub old_cluster_id: String,
1095    pub new_cluster_id: String,
1096}
1097
1098#[derive(
1099    Clone,
1100    Debug,
1101    Serialize,
1102    Deserialize,
1103    PartialOrd,
1104    PartialEq,
1105    Eq,
1106    Ord,
1107    Hash,
1108    Arbitrary
1109)]
1110pub struct GrantRoleV1 {
1111    pub role_id: String,
1112    pub member_id: String,
1113    pub grantor_id: String,
1114}
1115
1116#[derive(
1117    Clone,
1118    Debug,
1119    Serialize,
1120    Deserialize,
1121    PartialOrd,
1122    PartialEq,
1123    Eq,
1124    Ord,
1125    Hash,
1126    Arbitrary
1127)]
1128pub struct GrantRoleV2 {
1129    pub role_id: String,
1130    pub member_id: String,
1131    pub grantor_id: String,
1132    pub executed_by: String,
1133}
1134
1135#[derive(
1136    Clone,
1137    Debug,
1138    Serialize,
1139    Deserialize,
1140    PartialOrd,
1141    PartialEq,
1142    Eq,
1143    Ord,
1144    Hash,
1145    Arbitrary
1146)]
1147pub struct RevokeRoleV1 {
1148    pub role_id: String,
1149    pub member_id: String,
1150}
1151
1152#[derive(
1153    Clone,
1154    Debug,
1155    Serialize,
1156    Deserialize,
1157    PartialOrd,
1158    PartialEq,
1159    Eq,
1160    Ord,
1161    Hash,
1162    Arbitrary
1163)]
1164pub struct RevokeRoleV2 {
1165    pub role_id: String,
1166    pub member_id: String,
1167    pub grantor_id: String,
1168    pub executed_by: String,
1169}
1170
1171#[derive(
1172    Clone,
1173    Debug,
1174    Serialize,
1175    Deserialize,
1176    PartialOrd,
1177    PartialEq,
1178    Eq,
1179    Ord,
1180    Hash,
1181    Arbitrary
1182)]
1183pub struct UpdatePrivilegeV1 {
1184    pub object_id: String,
1185    pub grantee_id: String,
1186    pub grantor_id: String,
1187    pub privileges: String,
1188}
1189
1190#[derive(
1191    Clone,
1192    Debug,
1193    Serialize,
1194    Deserialize,
1195    PartialOrd,
1196    PartialEq,
1197    Eq,
1198    Ord,
1199    Hash,
1200    Arbitrary
1201)]
1202pub struct AlterDefaultPrivilegeV1 {
1203    pub role_id: String,
1204    pub database_id: Option<String>,
1205    pub schema_id: Option<String>,
1206    pub grantee_id: String,
1207    pub privileges: String,
1208}
1209
1210#[derive(
1211    Clone,
1212    Debug,
1213    Serialize,
1214    Deserialize,
1215    PartialOrd,
1216    PartialEq,
1217    Eq,
1218    Ord,
1219    Hash,
1220    Arbitrary
1221)]
1222pub struct UpdateOwnerV1 {
1223    pub object_id: String,
1224    pub old_owner_id: String,
1225    pub new_owner_id: String,
1226}
1227
1228#[derive(
1229    Clone,
1230    Debug,
1231    Serialize,
1232    Deserialize,
1233    PartialOrd,
1234    PartialEq,
1235    Eq,
1236    Ord,
1237    Hash,
1238    Arbitrary
1239)]
1240pub struct SchemaV1 {
1241    pub id: String,
1242    pub name: String,
1243    pub database_name: String,
1244}
1245
1246#[derive(
1247    Clone,
1248    Debug,
1249    Serialize,
1250    Deserialize,
1251    PartialOrd,
1252    PartialEq,
1253    Eq,
1254    Ord,
1255    Hash,
1256    Arbitrary
1257)]
1258pub struct SchemaV2 {
1259    pub id: String,
1260    pub name: String,
1261    pub database_name: Option<String>,
1262}
1263
1264#[derive(
1265    Clone,
1266    Debug,
1267    Serialize,
1268    Deserialize,
1269    PartialOrd,
1270    PartialEq,
1271    Eq,
1272    Ord,
1273    Hash,
1274    Arbitrary
1275)]
1276pub struct RenameSchemaV1 {
1277    pub id: String,
1278    pub database_name: Option<String>,
1279    pub old_name: String,
1280    pub new_name: String,
1281}
1282
1283#[derive(
1284    Clone,
1285    Debug,
1286    Serialize,
1287    Deserialize,
1288    PartialOrd,
1289    PartialEq,
1290    Eq,
1291    Ord,
1292    Hash,
1293    Arbitrary
1294)]
1295pub struct AlterRetainHistoryV1 {
1296    pub id: String,
1297    pub old_history: Option<String>,
1298    pub new_history: Option<String>,
1299}
1300
1301#[derive(
1302    Clone,
1303    Debug,
1304    Serialize,
1305    Deserialize,
1306    PartialOrd,
1307    PartialEq,
1308    Eq,
1309    Ord,
1310    Hash,
1311    Arbitrary
1312)]
1313pub struct AlterAddColumnV1 {
1314    pub id: String,
1315    pub column: String,
1316    pub column_type: String,
1317    pub nullable: bool,
1318}
1319
1320#[derive(
1321    Clone,
1322    Debug,
1323    Serialize,
1324    Deserialize,
1325    PartialOrd,
1326    PartialEq,
1327    Eq,
1328    Ord,
1329    Hash,
1330    Arbitrary
1331)]
1332pub struct AlterSourceTimestampIntervalV1 {
1333    pub id: String,
1334    pub old_interval: Option<String>,
1335    pub new_interval: Option<String>,
1336}
1337
1338#[derive(
1339    Clone,
1340    Debug,
1341    Serialize,
1342    Deserialize,
1343    PartialOrd,
1344    PartialEq,
1345    Eq,
1346    Ord,
1347    Hash,
1348    Arbitrary
1349)]
1350pub struct UpdateItemV1 {
1351    pub id: String,
1352    #[serde(flatten)]
1353    pub name: FullNameV1,
1354}
1355
1356#[derive(
1357    Clone,
1358    Debug,
1359    Serialize,
1360    Deserialize,
1361    PartialOrd,
1362    PartialEq,
1363    Eq,
1364    Ord,
1365    Hash,
1366    Arbitrary
1367)]
1368pub struct ToNewIdV1 {
1369    pub id: String,
1370    pub new_id: String,
1371}
1372
1373#[derive(
1374    Clone,
1375    Debug,
1376    Serialize,
1377    Deserialize,
1378    PartialOrd,
1379    PartialEq,
1380    Eq,
1381    Ord,
1382    Hash,
1383    Arbitrary
1384)]
1385pub struct FromPreviousIdV1 {
1386    pub id: String,
1387    pub previous_id: String,
1388}
1389
1390impl EventDetails {
1391    pub fn as_json(&self) -> serde_json::Value {
1392        match self {
1393            EventDetails::CreateClusterReplicaV1(v) => {
1394                serde_json::to_value(v).expect("must serialize")
1395            }
1396            EventDetails::CreateClusterReplicaV2(v) => {
1397                serde_json::to_value(v).expect("must serialize")
1398            }
1399            EventDetails::CreateClusterReplicaV3(v) => {
1400                serde_json::to_value(v).expect("must serialize")
1401            }
1402            EventDetails::CreateClusterReplicaV4(v) => {
1403                serde_json::to_value(v).expect("must serialize")
1404            }
1405            EventDetails::DropClusterReplicaV1(v) => {
1406                serde_json::to_value(v).expect("must serialize")
1407            }
1408            EventDetails::DropClusterReplicaV2(v) => {
1409                serde_json::to_value(v).expect("must serialize")
1410            }
1411            EventDetails::DropClusterReplicaV3(v) => {
1412                serde_json::to_value(v).expect("must serialize")
1413            }
1414            EventDetails::IdFullNameV1(v) => serde_json::to_value(v).expect("must serialize"),
1415            EventDetails::RenameClusterV1(v) => serde_json::to_value(v).expect("must serialize"),
1416            EventDetails::RenameClusterReplicaV1(v) => {
1417                serde_json::to_value(v).expect("must serialize")
1418            }
1419            EventDetails::AlterClusterReconfigurationV1(v) => {
1420                serde_json::to_value(v).expect("must serialize")
1421            }
1422            EventDetails::ClusterHydrationBurstV1(v) => {
1423                serde_json::to_value(v).expect("must serialize")
1424            }
1425            EventDetails::RenameItemV1(v) => serde_json::to_value(v).expect("must serialize"),
1426            EventDetails::IdNameV1(v) => serde_json::to_value(v).expect("must serialize"),
1427            EventDetails::SchemaV1(v) => serde_json::to_value(v).expect("must serialize"),
1428            EventDetails::SchemaV2(v) => serde_json::to_value(v).expect("must serialize"),
1429            EventDetails::RenameSchemaV1(v) => serde_json::to_value(v).expect("must serialize"),
1430            EventDetails::CreateSourceSinkV1(v) => serde_json::to_value(v).expect("must serialize"),
1431            EventDetails::CreateSourceSinkV2(v) => serde_json::to_value(v).expect("must serialize"),
1432            EventDetails::CreateSourceSinkV3(v) => serde_json::to_value(v).expect("must serialize"),
1433            EventDetails::CreateSourceSinkV4(v) => serde_json::to_value(v).expect("must serialize"),
1434            EventDetails::CreateIndexV1(v) => serde_json::to_value(v).expect("must serialize"),
1435            EventDetails::CreateMaterializedViewV1(v) => {
1436                serde_json::to_value(v).expect("must serialize")
1437            }
1438            EventDetails::AlterApplyReplacementV1(v) => {
1439                serde_json::to_value(v).expect("must serialize")
1440            }
1441            EventDetails::AlterSourceSinkV1(v) => serde_json::to_value(v).expect("must serialize"),
1442            EventDetails::AlterSetClusterV1(v) => serde_json::to_value(v).expect("must serialize"),
1443            EventDetails::GrantRoleV1(v) => serde_json::to_value(v).expect("must serialize"),
1444            EventDetails::GrantRoleV2(v) => serde_json::to_value(v).expect("must serialize"),
1445            EventDetails::RevokeRoleV1(v) => serde_json::to_value(v).expect("must serialize"),
1446            EventDetails::RevokeRoleV2(v) => serde_json::to_value(v).expect("must serialize"),
1447            EventDetails::UpdatePrivilegeV1(v) => serde_json::to_value(v).expect("must serialize"),
1448            EventDetails::AlterDefaultPrivilegeV1(v) => {
1449                serde_json::to_value(v).expect("must serialize")
1450            }
1451            EventDetails::UpdateOwnerV1(v) => serde_json::to_value(v).expect("must serialize"),
1452            EventDetails::UpdateItemV1(v) => serde_json::to_value(v).expect("must serialize"),
1453            EventDetails::AlterRetainHistoryV1(v) => {
1454                serde_json::to_value(v).expect("must serialize")
1455            }
1456            EventDetails::AlterAddColumnV1(v) => serde_json::to_value(v).expect("must serialize"),
1457            EventDetails::AlterSourceTimestampIntervalV1(v) => {
1458                serde_json::to_value(v).expect("must serialize")
1459            }
1460            EventDetails::ToNewIdV1(v) => serde_json::to_value(v).expect("must serialize"),
1461            EventDetails::FromPreviousIdV1(v) => serde_json::to_value(v).expect("must serialize"),
1462            EventDetails::SetV1(v) => serde_json::to_value(v).expect("must serialize"),
1463            EventDetails::ResetAllV1 => serde_json::Value::Null,
1464            EventDetails::RotateKeysV1(v) => serde_json::to_value(v).expect("must serialize"),
1465            EventDetails::CreateRoleV1(v) => serde_json::to_value(v).expect("must serialize"),
1466        }
1467    }
1468}
1469
1470#[derive(
1471    Clone,
1472    Debug,
1473    Serialize,
1474    Deserialize,
1475    PartialOrd,
1476    PartialEq,
1477    Eq,
1478    Ord,
1479    Hash,
1480    Arbitrary
1481)]
1482pub struct EventV1 {
1483    pub id: u64,
1484    pub event_type: EventType,
1485    pub object_type: ObjectType,
1486    pub details: EventDetails,
1487    pub user: Option<String>,
1488    pub occurred_at: EpochMillis,
1489}
1490
1491impl EventV1 {
1492    fn new(
1493        id: u64,
1494        event_type: EventType,
1495        object_type: ObjectType,
1496        details: EventDetails,
1497        user: Option<String>,
1498        occurred_at: EpochMillis,
1499    ) -> EventV1 {
1500        EventV1 {
1501            id,
1502            event_type,
1503            object_type,
1504            details,
1505            user,
1506            occurred_at,
1507        }
1508    }
1509}
1510
1511#[derive(
1512    Clone,
1513    Debug,
1514    Serialize,
1515    Deserialize,
1516    PartialOrd,
1517    PartialEq,
1518    Eq,
1519    Ord,
1520    Hash,
1521    Arbitrary
1522)]
1523pub struct StorageUsageV1 {
1524    pub id: u64,
1525    pub shard_id: Option<String>,
1526    pub size_bytes: u64,
1527    pub collection_timestamp: EpochMillis,
1528}
1529
1530impl StorageUsageV1 {
1531    pub fn new(
1532        id: u64,
1533        shard_id: Option<String>,
1534        size_bytes: u64,
1535        collection_timestamp: EpochMillis,
1536    ) -> StorageUsageV1 {
1537        StorageUsageV1 {
1538            id,
1539            shard_id,
1540            size_bytes,
1541            collection_timestamp,
1542        }
1543    }
1544}
1545
1546/// Describes the environment's storage usage at a point in time.
1547///
1548/// This type is persisted in the catalog across restarts, so any updates to the
1549/// schema will require a new version.
1550#[derive(
1551    Clone,
1552    Debug,
1553    Serialize,
1554    Deserialize,
1555    PartialOrd,
1556    PartialEq,
1557    Eq,
1558    Ord,
1559    Hash,
1560    Arbitrary
1561)]
1562pub enum VersionedStorageUsage {
1563    V1(StorageUsageV1),
1564}
1565
1566impl VersionedStorageUsage {
1567    /// Create a new metric snapshot.
1568    /// This function must always require and produce the most
1569    /// recent variant of VersionedStorageMetrics.
1570    pub fn new(
1571        id: u64,
1572        object_id: Option<String>,
1573        size_bytes: u64,
1574        collection_timestamp: EpochMillis,
1575    ) -> Self {
1576        Self::V1(StorageUsageV1::new(
1577            id,
1578            object_id,
1579            size_bytes,
1580            collection_timestamp,
1581        ))
1582    }
1583
1584    // Implement deserialize and serialize so writers and readers don't have to
1585    // coordinate about which Serializer to use.
1586    pub fn deserialize(data: &[u8]) -> Result<Self, anyhow::Error> {
1587        Ok(serde_json::from_slice(data)?)
1588    }
1589
1590    pub fn serialize(&self) -> Vec<u8> {
1591        serde_json::to_vec(self).expect("must serialize")
1592    }
1593
1594    pub fn timestamp(&self) -> EpochMillis {
1595        match self {
1596            VersionedStorageUsage::V1(StorageUsageV1 {
1597                collection_timestamp,
1598                ..
1599            }) => *collection_timestamp,
1600        }
1601    }
1602
1603    /// Returns a globally sortable event order. All event versions must have this
1604    /// field.
1605    pub fn sortable_id(&self) -> u64 {
1606        match self {
1607            VersionedStorageUsage::V1(usage) => usage.id,
1608        }
1609    }
1610}
1611
1612#[cfg(test)]
1613mod tests {
1614    use crate::{EventDetails, EventType, EventV1, IdNameV1, ObjectType, VersionedEvent};
1615
1616    // Test all versions of events. This test hard codes bytes so that
1617    // programmers are not able to change data structures here without this test
1618    // failing. Instead of changing data structures, add new variants.
1619    #[mz_ore::test]
1620    fn test_audit_log() -> Result<(), anyhow::Error> {
1621        let cases: Vec<(VersionedEvent, &'static str)> = vec![(
1622            VersionedEvent::V1(EventV1::new(
1623                2,
1624                EventType::Drop,
1625                ObjectType::ClusterReplica,
1626                EventDetails::IdNameV1(IdNameV1 {
1627                    id: "u1".to_string(),
1628                    name: "name".into(),
1629                }),
1630                None,
1631                2,
1632            )),
1633            r#"{"V1":{"id":2,"event_type":"drop","object_type":"cluster-replica","details":{"IdNameV1":{"id":"u1","name":"name"}},"user":null,"occurred_at":2}}"#,
1634        )];
1635
1636        for (event, expected_bytes) in cases {
1637            let event_bytes = serde_json::to_vec(&event).unwrap();
1638            assert_eq!(
1639                event_bytes,
1640                expected_bytes.as_bytes(),
1641                "expected bytes {}, got {}",
1642                expected_bytes,
1643                std::str::from_utf8(&event_bytes).unwrap(),
1644            );
1645        }
1646
1647        Ok(())
1648    }
1649}