Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

27.3 KB
Raw Blame
(ns metabase-enterprise.remote-sync.events
  "Event handlers for tracking model changes in remote-synced collections.

   Listens to Metabase model events (create/update/delete) and maintains the
   RemoteSyncObject table with the current sync status of each tracked model.
   This enables the remote sync system to know which objects have changed
   since the last sync operation.

   Event handlers are registered using specs from `metabase-enterprise.remote-sync.spec`.
   Each spec defines eligibility checking, field hydration, and other configuration.

   Tracked model types:
   - Card, Dashboard, Document, NativeQuerySnippet, Timeline, Collection
   - TableUserSettings, keyed by its Table (when the Table is published in a remote-synced collection)
   - FieldUserSettings and Dimension, keyed by their Field (when its Table is published in a remote-synced collection)
   - Segment, Measure (when belonging to a published table in a remote-synced collection)
   - Transform, TransformTag, transforms-namespace Collections (when remote-sync-transforms setting is enabled)
   - NativeQuerySnippet, snippets-namespace Collections, Glossary (when Library is remote-synced)"
  (:require
   [java-time.api :as t]
   [metabase-enterprise.remote-sync.db :as remote-sync.db]
   [metabase-enterprise.remote-sync.settings :as settings]
   [metabase-enterprise.remote-sync.source :as source]
   [metabase-enterprise.remote-sync.spec :as spec]
   [metabase.app-db.cluster-lock :as cluster-lock]
   [metabase.collections.core :as collections]
   [metabase.events.core :as events]
   [metabase.util.log :as log]
   [methodical.core :as methodical]
   [toucan2.core :as t2]))

(defn- glossary-tracking-rows
  "A 'create' ledger row for each of the glossary `entries`."
  [entries timestamp]
  (for [entry entries]
    {:model_type        "Glossary"
     :model_id          (:id entry)
     :model_name        (:term entry)
     :status            "create"
     :status_changed_at timestamp}))

(defn- data-action-collections
  "The `:id` and `:name` of the data actions Collections."
  []
  (remote-sync.db/collections-with-names-in-namespace (name collections/data-actions-ns)))

(defn- library-actions
  "The Actions without a model in the data actions root or a data actions Collection."
  [data-action-collection-ids]
  (remote-sync.db/actions-without-model-in (vec data-action-collection-ids)))

(defn enable-library-tracking!
  "Mark all existing snippets, data actions, their namespaces' collections, and glossary entries as 'create' for
  initial sync."
  []
  (let [timestamp               (t/offset-date-time)
        data-action-collections (data-action-collections)
        rows      (concat
                   (for [coll (concat (remote-sync.db/snippet-collections) data-action-collections)]
                     {:model_type        "Collection"
                      :model_id          (:id coll)
                      :model_name        (:name coll)
                      :status            "create"
                      :status_changed_at timestamp})
                   (for [snippet (remote-sync.db/snippets)]
                     {:model_type          "NativeQuerySnippet"
                      :model_id            (:id snippet)
                      :model_name          (:name snippet)
                      :model_collection_id (:collection_id snippet)
                      :status              "create"
                      :status_changed_at   timestamp})
                   (for [action (library-actions (map :id data-action-collections))]
                     {:model_type          "Action"
                      :model_id            (:id action)
                      :model_name          (:name action)
                      :model_collection_id (:collection_id action)
                      :status              "create"
                      :status_changed_at   timestamp})
                   (glossary-tracking-rows (remote-sync.db/glossary-entries) timestamp))]
    (when (seq rows)
      (remote-sync.db/insert-rsos! rows))))

(defn backfill-glossary-tracking!
  "Insert a 'create' ledger row for every glossary entry that has none, so an instance upgraded with the Library
  already synced still pushes its entries. Returns the number of rows inserted."
  []
  (let [rows (vec (glossary-tracking-rows (remote-sync.db/untracked-glossary-entries) (t/offset-date-time)))]
    (when (seq rows)
      (remote-sync.db/insert-rsos! rows))
    (count rows)))

(defn backfill-action-tracking!
  "Insert a 'create' ledger row for every unarchived Action in a remote-synced collection that has none, returning the
  number of rows inserted."
  []
  (let [action-spec    (spec/spec-for-model-key :model/Action)
        collection-ids (remote-sync.db/remote-synced-collection-ids)
        tracked        (remote-sync.db/tracked-model-ids "Action")
        timestamp      (t/offset-date-time)
        rows           (when (seq collection-ids)
                         (for [action (remote-sync.db/instances-in-collections :model/Action collection-ids :archived)
                               :when  (not (contains? tracked (:id action)))]
                           (merge {:model_type        "Action"
                                   :model_id          (:id action)
                                   :status            "create"
                                   :status_changed_at timestamp}
                                  (spec/build-sync-object-fields action-spec action))))]
    (when (seq rows)
      (remote-sync.db/insert-rsos! rows))
    (count rows)))

(defn disable-library-tracking!
  "Remove all snippet, data action, their namespaces' collection, and glossary tracking entries."
  []
  (let [data-action-coll-ids (into #{} (map :id) (data-action-collections))
        coll-ids             (into (remote-sync.db/snippet-collection-ids) data-action-coll-ids)
        action-ids           (into #{} (map :id) (library-actions data-action-coll-ids))]
    (remote-sync.db/delete-rsos-of-type! "NativeQuerySnippet")
    (remote-sync.db/delete-rsos-of-type! "Glossary")
    (when (seq coll-ids)
      (remote-sync.db/delete-rsos-of-models! "Collection" coll-ids))
    (when (seq action-ids)
      (remote-sync.db/delete-rsos-of-models! "Action" action-ids))))

(defn- transforms-folder-ids
  "The IDs of the transforms-namespace Collections."
  []
  (remote-sync.db/collection-ids-in-namespace (name collections/transforms-ns)))

(defn- transforms-rsos
  "The RemoteSyncObjects of transforms content: every model that syncs with transforms, and the transforms folders."
  []
  (concat (remote-sync.db/rsos-of-types (vec (spec/models-for-setting :remote-sync-transforms)))
          (when-let [folder-ids (seq (transforms-folder-ids))]
            (remote-sync.db/rsos-of-models "Collection" (vec folder-ids)))))

(defn- untracked-row
  "A 'create' RemoteSyncObject row for `instance` of `model-type`."
  [model-type instance timestamp]
  (merge {:model_type        model-type
          :model_id          (:id instance)
          :status            "create"
          :status_changed_at timestamp}
         (spec/build-sync-object-fields (spec/spec-for-model-type model-type) instance)))

(defn- untracked-transforms-rows
  "A 'create' row for each piece of transforms content that an export writes and that has no row yet."
  [timestamp]
  (let [exportable (update-vals (spec/exportable-entities) set)
        untracked? (fn [model-type tracked instance]
                     (and (contains? (get exportable model-type) (:id instance))
                          (not (contains? tracked (:id instance)))))]
    (concat
     (for [model-type (sort (spec/models-for-setting :remote-sync-transforms))
           :let       [model-spec (spec/spec-for-model-type model-type)
                       tracked    (remote-sync.db/tracked-model-ids model-type)]
           instance   (remote-sync.db/instances-where (:model-key model-spec) (spec/export-conditions model-spec))
           :when      (untracked? model-type tracked instance)]
       (untracked-row model-type instance timestamp))
     (let [tracked (remote-sync.db/tracked-model-ids "Collection")]
       (for [folder (remote-sync.db/collections-with-names-in-namespace (name collections/transforms-ns))
             :when  (untracked? "Collection" tracked folder)]
         (untracked-row "Collection" folder timestamp))))))

(defn- removed-rsos-by-existence
  "`removed` RemoteSyncObjects split into those whose entity still exists (`true`) and those whose entity is gone
  (`false`)."
  [removed]
  (let [existing (into {}
                       (for [[model-type rsos] (group-by :model_type removed)]
                         [model-type (remote-sync.db/existing-ids (:model-key (spec/spec-for-model-type model-type))
                                                                  (mapv :model_id rsos))]))]
    (group-by #(contains? (existing (:model_type %)) (:model_id %)) removed)))

(defn enable-transforms-tracking!
  "Tracks the transforms content: a 'removed' row becomes an update again, or a delete when its entity is gone, and
  exported content without a row gets a 'create' row."
  []
  (let [timestamp              (t/offset-date-time)
        {live true gone false} (removed-rsos-by-existence (filterv #(= "removed" (:status %)) (transforms-rsos)))
        rows                   (vec (untracked-transforms-rows timestamp))]
    (when (seq live)
      (remote-sync.db/set-rsos-status! (mapv :id live) "update" timestamp))
    (when (seq gone)
      (remote-sync.db/set-rsos-status! (mapv :id gone) "delete" timestamp))
    (when (seq rows)
      (remote-sync.db/insert-rsos! rows))))

(defn disable-transforms-tracking!
  "Stops tracking the transforms content: rows never pushed are dropped, and pushed ones become 'removed', so the next
  push deletes their files while the content stays."
  []
  (let [timestamp (t/offset-date-time)
        rsos      (transforms-rsos)
        created   (filterv #(= "create" (:status %)) rsos)
        pushed    (filterv #(#{"synced" "update"} (:status %)) rsos)]
    (when (seq created)
      (remote-sync.db/delete-rsos! (mapv :id created)))
    (when (seq pushed)
      (remote-sync.db/set-rsos-status! (mapv :id pushed) "removed" timestamp))))

(def ^:private legacy-transforms-root-id
  "The model_id of the Collection RemoteSyncObject that stood for all of transforms before they were tracked per row."
  -1)

(defn- do-with-transforms-tracking-lock
  "Calls `thunk` in one transaction, holding the cluster lock that serializes changes to the transforms tracking."
  [thunk]
  (cluster-lock/with-cluster-lock ::transforms-tracking
    (t2/with-transaction [_conn]
      (thunk))))

(defn convert-legacy-transforms-root!
  "Replaces the legacy Transforms root RemoteSyncObject with per-row tracking, once across the cluster: a pending
  'create' or 'update' tracks the transforms content, a pending 'delete' marks it removed, and the root row goes."
  []
  (when (remote-sync.db/rso "Collection" legacy-transforms-root-id)
    (do-with-transforms-tracking-lock
     (fn []
       (when-let [{:keys [status]} (remote-sync.db/rso "Collection" legacy-transforms-root-id)]
         (case status
           ("create" "update") (enable-transforms-tracking!)
           "delete"            (disable-transforms-tracking!)
           nil)
         (remote-sync.db/delete-rso-of! "Collection" legacy-transforms-root-id))))))

(defn sync-transforms-tracking!
  "Brings the transforms tracking in line with [[settings/remote-sync-transforms]] on a read-write instance, which is
  the only kind that publishes."
  []
  (when (= :read-write (settings/remote-sync-type))
    (do-with-transforms-tracking-lock
     (fn []
       (if (settings/remote-sync-transforms)
         (enable-transforms-tracking!)
         (disable-transforms-tracking!))))))

;;; ----------------------------------------- Helper Functions ---------------------------------------------------------

(defn- resolve-status
  "Suppresses a no-op 'update' whose content_hash and stored file_path both still match, otherwise keeps status
  unchanged."
  [model-type model-id status existing]
  (if (or (not= "update" status)
          (nil? (:content_hash existing)))
    status
    (let [{:keys [path content-hash]} (source/row->file-info {:model_type model-type :model_id model-id})]
      (if (and (= (:content_hash existing) content-hash)
               (or (nil? (:file_path existing))
                   (= (:file_path existing) path)))
        "synced"
        status))))

(defn- create-or-update-remote-sync-object-entry!
  "Creates or updates a remote sync object entry for a model change.

   Parameters:
   - model-type: Type of model ('Card', 'Dashboard', 'Document', 'Collection', etc.)
   - model-id: ID of the affected model
   - status: Sync status ('create', 'update', 'removed', 'delete', 'error', 'synced')
   - hydrate-details-fn: Function that takes model-id and returns a map with :name, :collection_id,
                         and optionally :display, :table_id, :table_name"
  [model-type model-id status hydrate-details-fn]
  (let [existing (remote-sync.db/rso model-type model-id)]
    (cond
      (not existing)
      (let [model-details (hydrate-details-fn model-id)]
        (remote-sync.db/insert-rso!
         {:model_type model-type
          :model_id model-id
          :model_name (:name model-details)
          :model_collection_id (:collection_id model-details)
          :model_display (some-> model-details :display name)
          :model_table_id (:table_id model-details)
          :model_table_name (:table_name model-details)
          :status status
          :status_changed_at (t/offset-date-time)}))
      (and (= "create" (:status existing)) (contains? #{"removed" "delete"} status))
      (remote-sync.db/delete-rso! (:id existing))
      (= "delete" (:status existing))
      (remote-sync.db/update-rso! (:id existing)
                                  {:status status
                                   :status_changed_at (t/offset-date-time)})
      (not (= "create" (:status existing)))
      (let [model-details (hydrate-details-fn model-id)]
        (remote-sync.db/update-rso! (:id existing)
                                    {:status (resolve-status model-type model-id status existing)
                                     :status_changed_at (t/offset-date-time)
                                     :model_name (:name model-details)
                                     :model_collection_id (:collection_id model-details)
                                     :model_display (some-> model-details :display name)
                                     :model_table_id (:table_id model-details)
                                     :model_table_name (:table_name model-details)})))))

;;; ----------------------------------------- Spec-based Event Handling ------------------------------------------------

(defn- still-eligible?
  "Re-checks `model-id`'s eligibility against current DB state. The eligibility that got us here was computed
   from an event payload, which a concurrent change may have invalidated in the meantime."
  [model-spec model-id]
  (boolean (when-let [instance (remote-sync.db/instance (spec/source-model model-spec) model-id)]
             (and (spec/check-eligibility model-spec instance)
                  (spec/row-exists? model-spec model-id)))))

(defn- create-or-update-sync-object-from-spec!
  "Creates or updates a RemoteSyncObject entry using a spec for field hydration.
   This is the spec-based version of create-or-update-remote-sync-object-entry!.

   Row-locks the entry for the transaction, so this and a concurrent un-sync of the entity's collection
   settle in a fixed order rather than losing one of the two writes: whichever locks first commits, and
   the other then observes that result — the un-sync re-marking the row, or the eligibility re-check below
   seeing the entity is gone from the synced set."
  [model-spec model-id status]
  (t2/with-transaction [_conn]
    (let [model-type (:model-type model-spec)
          existing   (remote-sync.db/lock-rso model-type model-id)]
      (cond
        (and (not existing)
             (contains? #{"removed" "delete"} status))
        nil

        ;; No row to lock, so a concurrent un-sync that hasn't inserted yet is invisible here (a phantom the
        ;; row lock can't cover). Re-check eligibility so a stale tracked-status event does not start tracking
        ;; an entity that has since left the synced set. This narrows, but cannot fully close, that window.
        (and (not existing)
             (not (still-eligible? model-spec model-id)))
        nil

        (not existing)
        (let [model-details (spec/hydrate-model-details model-spec model-id)
              fields        (spec/build-sync-object-fields model-spec model-details)]
          (remote-sync.db/insert-rso!
           (merge {:model_type        model-type
                   :model_id          model-id
                   :status            status
                   :status_changed_at (t/offset-date-time)}
                  fields)))

        (and (= "create" (:status existing)) (contains? #{"removed" "delete"} status))
        (remote-sync.db/delete-rso! (:id existing))

        ;; A pending removal must not be resurrected by a tracked-status write whose eligibility check was
        ;; overtaken by a concurrent un-sync: that check ran against the event payload, well before this
        ;; write, so re-check against current state and let the removal stand when it no longer holds.
        (and (contains? #{"removed" "delete"} (:status existing))
             (not (contains? #{"removed" "delete"} status))
             (not (still-eligible? model-spec model-id)))
        nil

        (= "delete" (:status existing))
        (remote-sync.db/update-rso! (:id existing)
                                    {:status            status
                                     :status_changed_at (t/offset-date-time)})

        (not= "create" (:status existing))
        (let [model-details (spec/hydrate-model-details model-spec model-id)
              fields        (spec/build-sync-object-fields model-spec model-details)]
          (remote-sync.db/update-rso! (:id existing)
                                      (merge {:status            (resolve-status model-type model-id status existing)
                                              :status_changed_at (t/offset-date-time)}
                                             fields)))))))

(defn- cascade-filter
  "Derives the filter conditions for querying eligible children from a child spec."
  [child-spec]
  (or (:cascade-filter child-spec)
      (when-let [ak (:archived-key child-spec)]
        {ak false})))

(defn- user-settings-child-ids
  "The ids of the Fields of the Table with `table-id` that have the `child-spec` user settings."
  [child-spec table-id]
  (case (:model-key child-spec)
    :model/FieldUserSettings (remote-sync.db/field-ids-with-user-settings [table-id])
    :model/Dimension         (remote-sync.db/field-ids-with-dimensions [table-id])))

(defn- cascade-to-children!
  "When a parent model becomes eligible/ineligible, cascade to its children.
   For eligible: query child entities using :parent-fk and derived filter, check eligibility, create RSOs.
   For ineligible: query existing RSOs by model_table_id and mark as removed."
  [model-spec model-id status eligible?]
  (doseq [child-spec (spec/children-specs (:model-key model-spec))
          child-id   (cond
                       (and eligible? (= :user-settings (:identity child-spec)))
                       (user-settings-child-ids child-spec model-id)

                       eligible?
                       (for [child (remote-sync.db/eligible-children (:model-key child-spec) (:parent-fk child-spec)
                                                                     model-id (cascade-filter child-spec))
                             :when (spec/check-eligibility child-spec child)]
                         (:id child))

                       :else
                       (map :model_id (remote-sync.db/active-child-rsos (:model-type child-spec) model-id)))]
    (create-or-update-sync-object-from-spec! child-spec child-id (if eligible? status "removed"))))

(defn- handle-model-event-from-spec
  "Generic event handler that uses a spec for all configuration.
   Checks eligibility, determines status, and creates/updates the sync object."
  [model-spec topic {:keys [object]}]
  (let [model-type     (:model-type model-spec)
        model-id       (:id object)
        eligible?      (and (spec/check-eligibility model-spec object)
                            (spec/row-exists? model-spec model-id))
        existing-entry (remote-sync.db/rso model-type model-id)
        status         (spec/determine-status model-spec topic object)]
    (cond
      ;; a synced item on a read-only instance can still change (e.g. an admin's public link), but that change can
      ;; never be pushed, so tracking it would only block the next pull
      (not (spec/model-editable? (:model-key model-spec) object))
      nil

      eligible?
      (do
        (log/infof "Creating remote sync object entry for %s %s (status: %s)"
                   model-type model-id status)
        (create-or-update-sync-object-from-spec! model-spec model-id status)
        (when (seq (spec/children-specs (:model-key model-spec)))
          (cascade-to-children! model-spec model-id status true)))
      (and existing-entry (not eligible?))
      (do
        (log/infof "%s %s moved out of sync scope, marking as removed" model-type model-id)
        (create-or-update-sync-object-from-spec! model-spec model-id "removed")
        (when (seq (spec/children-specs (:model-key model-spec)))
          (cascade-to-children! model-spec model-id "removed" false))))))

(defn- register-events-for-spec!
  "Registers event handlers for a single spec. Creates event hierarchy and
   registers a methodical handler for the parent event."
  [model-spec]
  (let [event-kws (spec/event-keywords model-spec)
        parent-kw (:parent event-kws)]
    (events/derive! parent-kw :metabase/event)
    (doseq [[_event-type event-kw] (dissoc event-kws :parent)]
      (events/derive! event-kw parent-kw))
    (methodical/add-primary-method!
     #'events/publish-event!
     parent-kw
     (fn [topic event]
       (handle-model-event-from-spec model-spec topic event)))))

;;; --------------------------------- Spec-based Event Registration (Non-Collection) -----------------------------------

(doseq [[_model-key model-spec] (dissoc spec/remote-sync-specs :model/Collection)]
  (register-events-for-spec! model-spec))

;;; ----------------------------------------- Collection Event Handler -------------------------------------------------
;; Collection has special handling due to side effects (tracking published tables when
;; a collection becomes remote-synced). This handler is kept separate from the standard
;; spec-based registration.

(events/derive! ::collection-change-event :metabase/event)
(events/derive! :event/collection-create ::collection-change-event)
(events/derive! :event/collection-update ::collection-change-event)

(defn- hydrate-collection-details
  "Hydrates details for a Collection."
  [id]
  (remote-sync.db/collection-name-and-id id))

(defn- handle-library-sync-status-change!
  "When the Library collection's is_remote_synced status changes, trigger Library content sync tracking.
   This ensures all snippets and glossary entries are tracked/untracked when Library sync is enabled/disabled."
  [is-now-synced?]
  (let [library-already-tracked? (or (remote-sync.db/rso-of-type-exists? "NativeQuerySnippet")
                                     (remote-sync.db/rso-of-type-exists? "Glossary"))]
    (cond
      (and is-now-synced? (not library-already-tracked?))
      (do
        (log/info "Library collection became remote-synced, enabling Library content sync tracking")
        (enable-library-tracking!))
      (and (not is-now-synced?) library-already-tracked?)
      (do
        (log/info "Library collection is no longer remote-synced, disabling Library content sync tracking")
        (disable-library-tracking!)))))

(defn- cascade-archived-state!
  "Brings the RemoteSyncObject rows of `collection`'s subtree, other than its own row, in line with the archived state
  of each entity and of the collection it is in: rows of entities that are archived or in an archived collection
  become 'delete', and 'delete' rows of existing entities that are neither become 'update'."
  [collection]
  ;; Archiving a collection archives its subtree in bulk SQL, which publishes no event per descendant. Transforms
  ;; have no archived column, so only their collection shows that they were archived.
  (let [collection-ids       (remote-sync.db/subtree-collection-ids [collection])
        collection-archived? (remote-sync.db/archived-by-id :model/Collection (vec collection-ids))
        rows                 (->> (remote-sync.db/content-rsos collection-ids)
                                  (remove #(and (= "Collection" (:model_type %)) (= (:id collection) (:model_id %)))))
        now                  (t/offset-date-time)]
    (doseq [[model-type type-rows] (group-by :model_type rows)
            :let  [{:keys [model-key archived-key]} (spec/spec-for-model-type model-type)]
            :when (= :archived archived-key)
            :let  [entity-archived? (remote-sync.db/archived-by-id model-key (mapv :model_id type-rows))
                   archived?        (fn [{:keys [model_id model_collection_id]}]
                                      (or (true? (entity-archived? model_id))
                                          (true? (collection-archived? model_collection_id))))
                   deleted          (filter #(and (archived? %)
                                                  (not (contains? #{"delete" "removed"} (:status %))))
                                            type-rows)
                   restored         (filter #(and (contains? entity-archived? (:model_id %))
                                                  (not (archived? %))
                                                  (= "delete" (:status %)))
                                            type-rows)]]
      (when (seq deleted)
        (remote-sync.db/set-rsos-status! (map :id deleted) "delete" now))
      (when (seq restored)
        (remote-sync.db/set-rsos-status! (map :id restored) "update" now)))))

(methodical/defmethod events/publish-event! ::collection-change-event
  [topic event]
  (let [{:keys [object]} event
        should-sync? (spec/should-sync-collection? object)
        is-remote-synced? (collections/remote-synced-collection? object)
        existing-entry (remote-sync.db/rso "Collection" (:id object))
        status (if (:archived object)
                 "delete"
                 (case topic
                   :event/collection-create "create"
                   :event/collection-update "update"))]
    (when (and (= topic :event/collection-update)
               (spec/library-collection? object))
      (handle-library-sync-status-change! is-remote-synced?))
    (cond
      should-sync?
      (do
        (log/infof "Creating remote sync object entry for collection %s (status: %s)" (:id object) status)
        (create-or-update-remote-sync-object-entry! "Collection" (:id object) status hydrate-collection-details)
        (when (and (= topic :event/collection-update)
                   (or (:archived object) (= "delete" (:status existing-entry))))
          (cascade-archived-state! object)))
      (and existing-entry (not should-sync?))
      (do
        (log/infof "Collection %s no longer needs syncing, marking as removed" (:id object))
        (create-or-update-remote-sync-object-entry! "Collection" (:id object) "removed" hydrate-collection-details)))))