diff --git a/common-app-lib/src/cmr/common_app/api/request_logger.clj b/common-app-lib/src/cmr/common_app/api/request_logger.clj index c9c830f3a1..de2309efc4 100644 --- a/common-app-lib/src/cmr/common_app/api/request_logger.clj +++ b/common-app-lib/src/cmr/common_app/api/request_logger.clj @@ -11,9 +11,13 @@ [cmr.common.log :as log :refer [error report]] [cmr.common.util :as util] [cmr.common.time-keeper :as tk] - [digest :as digest] [ring.middleware.params :as params] - [ring.util.codec :as codec])) + [ring.util.codec :as codec]) + (:import + (java.io OutputStream OutputStreamWriter) + (java.nio.charset Charset) + (java.security DigestOutputStream MessageDigest) + (java.util HexFormat))) (defn- request->uri "Reconstruct a url that a request client may have asked for (assuming port @@ -85,6 +89,31 @@ (util/remove-nil-keys)) data))) +(def ^:private hash-chunk-length + "Number of characters encoded at a time when hashing a response body." + 8192) + +(defn- md5-and-sha1 + "Returns the hex MD5 and SHA-1 digests of text, encoding it a chunk at a time + instead of copying the whole string into a byte array." + [^String text] + (let [md5 (MessageDigest/getInstance "MD5") + sha1 (MessageDigest/getInstance "SHA-1") + length (.length text) + buffer (char-array (min length hash-chunk-length))] + ;; Default charset matches the String.getBytes the digest library used, so header values are unchanged. + (with-open [writer (OutputStreamWriter. + (DigestOutputStream. (DigestOutputStream. (OutputStream/nullOutputStream) md5) sha1) + (Charset/defaultCharset))] + (loop [start 0] + (when (< start length) + (let [end (min length (+ start (alength buffer)))] + (.getChars text start end buffer 0) + (.write writer buffer 0 (- end start)) + (recur end))))) + [(.formatHex (HexFormat/of) (.digest md5)) + (.formatHex (HexFormat/of) (.digest sha1))])) + ;; ***************************************************************************** ;; Ring Middleware Handlers @@ -98,9 +127,7 @@ (fn [request] (let [response (handler request) ;; This is run after all responses - text (str (:body response)) - body-md5 (digest/md5 text) - body-sha1 (digest/sha-1 text) + [body-md5 body-sha1] (md5-and-sha1 (str (:body response))) updated-response (-> response (assoc-in [:headers "Content-MD5"] body-md5) (assoc-in [:headers "Content-SHA1"] body-sha1))] diff --git a/common-app-lib/test/cmr/common_app/test/api/request_logger.clj b/common-app-lib/test/cmr/common_app/test/api/request_logger.clj index 8483bdd951..16e77e05ef 100644 --- a/common-app-lib/test/cmr/common_app/test/api/request_logger.clj +++ b/common-app-lib/test/cmr/common_app/test/api/request_logger.clj @@ -3,7 +3,16 @@ (:require [clojure.test :refer [deftest is testing]] [cmr.common-app.api.request-logger :as req-logger] - [cmr.common.util :as util :refer [are3]])) + [cmr.common.util :as util :refer [are3]] + [digest :as digest])) + +(deftest add-body-hashes-test + (testing "hash headers match the digest library for multibyte text spanning chunks" + (let [body (str (apply str (repeat 8191 "a")) "😀 café 中文") + handler (req-logger/add-body-hashes (constantly {:status 200 :body body})) + headers (:headers (handler {}))] + (is (= (digest/md5 body) (get headers "Content-MD5"))) + (is (= (digest/sha-1 body) (get headers "Content-SHA1")))))) (defn basic-request [options] diff --git a/metadata-db-app/src/cmr/metadata_db/config.clj b/metadata-db-app/src/cmr/metadata_db/config.clj index 0ae26c5dc2..e84111f59f 100644 --- a/metadata-db-app/src/cmr/metadata_db/config.clj +++ b/metadata-db-app/src/cmr/metadata_db/config.clj @@ -40,6 +40,12 @@ {:default 200 :type Long}) +(defconfig parallel-chunk-threads + "Maximum number of chunks one get-concepts or get-latest-concepts call fetches at once, each on + its own database connection." + {:default 2 + :type Long}) + (defconfig result-set-fetch-size "Gets the setting for query fetch-size (number of rows to fetch at once)" {:default 200 diff --git a/metadata-db-app/src/cmr/metadata_db/data/oracle/concepts.clj b/metadata-db-app/src/cmr/metadata_db/data/oracle/concepts.clj index dcc4d5aae7..fc4975f2b8 100644 --- a/metadata-db-app/src/cmr/metadata_db/data/oracle/concepts.clj +++ b/metadata-db-app/src/cmr/metadata_db/data/oracle/concepts.clj @@ -179,37 +179,49 @@ ;; we want the temp table to persist for the main select (concat concept-id-revision-id-tuples [:transaction? false]))) +(def ^:private max-in-list-size + "Maximum number of items in one IN list." + 64) + +(defn- in-list-batches + "Splits items into batches of at most max-in-list-size, padding each with its last item to + either 8 or max-in-list-size items." + [items] + (for [batch (partition-all max-in-list-size items) + :let [size (count batch) + padded-size (if (<= size 8) 8 max-in-list-size)]] + ;; Each list length is a separate cursor whose shared pool memory grows ~3 KB per item, so keep two short lengths. + (concat batch (repeat (- padded-size size) (last batch))))) + +(defn- in-list-placeholders + "Returns n comma separated copies of placeholder." + [n placeholder] + (string/join "," (repeat n placeholder))) + (defn get-latest-concept-id-revision-id-tuples "Finds the latest pairs of concept id and revision ids for the given concept ids. If no revisions exist for a given concept id it will not be returned." [db concept-type provider concept-ids] - (let [start (System/currentTimeMillis)] - (j/with-db-transaction - [conn db] - ;; use a temporary table to insert our values so we can use a join to - ;; pull everything in one select - (apply j/insert! conn - "get_concepts_work_area" - ["concept_id"] - ;; set :transaction? false since we are already inside a transaction, and - ;; we want the temp table to persist for the main select - (concat (map vector concept-ids) [:transaction? false])) - ;; pull back all revisions of each concept-id and then take the latest - ;; instead of using group-by in SQL - (let [table (tables/get-table-name provider concept-type) - stmt (su/build (select [:c.concept-id :c.revision-id] - (from (as (keyword table) :c) - (as :get-concepts-work-area :t)) - (where `(and (= :c.concept-id :t.concept-id))))) - cid-rid-maps (su/query conn stmt) - concept-id-to-rev-id-maps (map #(hash-map (:concept_id %) (long (:revision_id %))) - cid-rid-maps) - latest (apply merge-with safe-max {} - concept-id-to-rev-id-maps) - concept-id-revision-id-tuples (seq latest) - latest-time (- (System/currentTimeMillis) start)] - (debug (format "Retrieving latest revision-ids took [%d] ms" latest-time)) - concept-id-revision-id-tuples)))) + (let [start (System/currentTimeMillis) + table (tables/get-table-name provider concept-type) + cid-rid-maps (j/with-db-connection + [conn db] + (doall + (mapcat (fn [batch] + (su/query conn (into [(format "SELECT concept_id, revision_id FROM %s WHERE concept_id IN (%s)" + table (in-list-placeholders (count batch) "?"))] + batch))) + (in-list-batches concept-ids)))) + ;; pull back all revisions of each concept-id and then take the latest + ;; instead of using group-by in SQL + concept-id-to-rev-id-maps (map #(hash-map (:concept_id %) (long (:revision_id %))) + cid-rid-maps) + latest (apply merge-with safe-max {} + concept-id-to-rev-id-maps) + concept-id-revision-id-tuples (seq latest) + latest-time (- (System/currentTimeMillis) start)] + (debug (format "Retrieving latest revision-ids took [%d] ms" latest-time)) + concept-id-revision-id-tuples)) (defn validate-concept-id-native-id-not-changing "Validates that the concept-id native-id pair for a concept being saved is not changing. This @@ -370,23 +382,21 @@ (defn get-concepts [db concept-type provider concept-id-revision-id-tuples] (if (pos? (count concept-id-revision-id-tuples)) - (let [start (System/currentTimeMillis)] - (j/with-db-transaction + (let [start (System/currentTimeMillis) + provider-id (:provider-id provider) + table (tables/get-table-name provider concept-type)] + ;; No temp table insert or transaction, so reads generate no undo or redo and need no commit. + (j/with-db-connection [conn db] - ;; use a temporary table to insert our values so we can use a join to - ;; pull everything in one select - (save-concepts-to-tmp-table conn concept-id-revision-id-tuples) - - (let [provider-id (:provider-id provider) - table (tables/get-table-name provider concept-type) - stmt (su/build (select [:c.*] - (from (as (keyword table) :c) - (as :get-concepts-work-area :t)) - (where `(and (= :c.concept-id :t.concept-id) - (= :c.revision-id :t.revision-id))))) - - result (doall (map (partial db-result->concept-map concept-type conn provider-id) - (su/query conn stmt))) + (let [concepts-by-tuple (into {} + (for [batch (in-list-batches concept-id-revision-id-tuples) + row (su/query conn (into [(format "SELECT * FROM %s WHERE (concept_id, revision_id) IN (%s)" + table (in-list-placeholders (count batch) "(?,?)"))] + (apply concat batch))) + :let [concept (db-result->concept-map concept-type conn provider-id row)]] + [[(:concept-id concept) (:revision-id concept)] concept])) + ;; One result per requested tuple, duplicates included, for get-concepts' count check. + result (doall (keep concepts-by-tuple concept-id-revision-id-tuples)) millis (- (System/currentTimeMillis) start)] (debug (format "Getting [%d] concepts took [%d] ms" (count result) millis)) result))) diff --git a/metadata-db-app/src/cmr/metadata_db/services/concept_service.clj b/metadata-db-app/src/cmr/metadata_db/services/concept_service.clj index 0cdfd018f5..471dce1844 100644 --- a/metadata-db-app/src/cmr/metadata_db/services/concept_service.clj +++ b/metadata-db-app/src/cmr/metadata_db/services/concept_service.clj @@ -528,6 +528,15 @@ provider (errors/throw-service-error :not-found (msg/provider-does-not-exist provider-id)))) +(defn- fetch-in-chunks + "Calls fetch-fn on chunks of chunk-size items, running at most max-threads chunks at once, and + returns all the results." + [fetch-fn chunk-size max-threads items] + (let [chunks (vec (partition-all chunk-size items)) + chunks-per-thread (long (Math/ceil (/ (count chunks) (double (max 1 max-threads)))))] + (apply concat + (cutil/pmap-n-all #(doall (mapcat fetch-fn %)) chunks-per-thread chunks)))) + (defn get-concepts "Get multiple concepts by concept-id and revision-id. Returns concepts in order requested" [context concept-id-revision-id-tuples allow-missing?] @@ -535,6 +544,7 @@ (count concept-id-revision-id-tuples))) (let [start (System/currentTimeMillis) parallel-chunk-size (get-in context [:system :parallel-chunk-size]) + parallel-chunk-threads (get-in context [:system :parallel-chunk-threads]) db (util/context->db context) providers (conj (provider-db/get-providers db) pv/cmr-provider) ;; Split the tuples so they can be requested separately for each provider and concept type @@ -552,11 +562,10 @@ (if (and (> parallel-chunk-size 0) (< parallel-chunk-size (count tuples))) ;; retrieving chunks in parallel for faster read performance - (apply concat - (cutil/pmap-n-all - (partial c/get-concepts db concept-type provider) - parallel-chunk-size - tuples)) + (fetch-in-chunks (partial c/get-concepts db concept-type provider) + parallel-chunk-size + parallel-chunk-threads + tuples) (c/get-concepts db concept-type provider tuples)))) ;; Create a map of tuples to concepts concepts-by-tuple (into {} (for [c concepts] [[(:concept-id c) (:revision-id c)] c]))] @@ -586,6 +595,7 @@ (doall (reduce #(str %1 " " %2) "" concept-ids)))) start (System/currentTimeMillis) parallel-chunk-size (get-in context [:system :parallel-chunk-size]) + parallel-chunk-threads (get-in context [:system :parallel-chunk-threads]) db (util/context->db context) providers (conj (provider-db/get-providers db) pv/cmr-provider) ;; Split the concept-ids so they can be requested separately for each provider and concept type @@ -603,11 +613,10 @@ (if (and (> parallel-chunk-size 0) (< parallel-chunk-size (count cids))) ;; retrieving chunks in parallel for faster read performance - (apply concat - (cutil/pmap-n-all - (partial c/get-latest-concepts db concept-type provider) - parallel-chunk-size - cids)) + (fetch-in-chunks (partial c/get-latest-concepts db concept-type provider) + parallel-chunk-size + parallel-chunk-threads + cids) (c/get-latest-concepts db concept-type provider cids)))) ;; Create a map of concept-ids to concepts concepts-by-concept-id (into {} (for [c concepts] [(:concept-id c) c]))] diff --git a/metadata-db-app/src/cmr/metadata_db/system.clj b/metadata-db-app/src/cmr/metadata_db/system.clj index 76b33cf2b6..5422af6257 100644 --- a/metadata-db-app/src/cmr/metadata_db/system.clj +++ b/metadata-db-app/src/cmr/metadata_db/system.clj @@ -45,6 +45,7 @@ :web (web/create-web-server (transmit-config/metadata-db-port) routes/make-api) :nrepl (nrepl/create-nrepl-if-configured (config/metadata-db-nrepl-port)) :parallel-chunk-size (config/parallel-chunk-size) + :parallel-chunk-threads (config/parallel-chunk-threads) :caches {acl/token-imp-cache-key (acl/create-token-imp-cache) common-health/health-cache-key (common-health/create-health-cache)} :scheduler (jobs/create-clustered-scheduler `system-holder :db mdb-jobs/jobs) diff --git a/metadata-db-app/test/cmr/metadata_db/test/data/oracle/concepts.clj b/metadata-db-app/test/cmr/metadata_db/test/data/oracle/concepts.clj index 610d87c8e2..27f6f46e12 100644 --- a/metadata-db-app/test/cmr/metadata_db/test/data/oracle/concepts.clj +++ b/metadata-db-app/test/cmr/metadata_db/test/data/oracle/concepts.clj @@ -87,3 +87,11 @@ "parent_collection_id" "delete_time" "granule_ur" "provider_id"] ["foo" "G7-PROV1" "" "ECHO10" 2 false "C5-PROV1" sql-timestamp "foo-ur" "PROV1"]] (fix-result (c/concept->insert-args concept true))))))) + +(deftest in-list-batches-test + (let [in-list-batches #'c/in-list-batches + items (range 600) + batches (in-list-batches items)] + (is (= (repeat 10 64) (map count batches))) + (is (= [1 2 3 3 3 3 3 3] (first (in-list-batches [1 2 3]))) "Pads short lists with the last item to 8") + (is (= (set items) (set (apply concat batches)))))) diff --git a/metadata-db-app/test/cmr/metadata_db/test/services/concept_service.clj b/metadata-db-app/test/cmr/metadata_db/test/services/concept_service.clj index 01945f2e40..cdc6ed69b1 100644 --- a/metadata-db-app/test/cmr/metadata_db/test/services/concept_service.clj +++ b/metadata-db-app/test/cmr/metadata_db/test/services/concept_service.clj @@ -254,3 +254,15 @@ "sets a collection concept id." (dissoc example-concept :concept-id))))) + +(deftest fetch-in-chunks-test + (let [fetch-in-chunks #'cs/fetch-in-chunks + running (atom 0) + peak (atom 0) + fetch (fn [chunk] + (swap! peak max (swap! running inc)) + (Thread/sleep 20) + (swap! running dec) + chunk)] + (is (= (range 2000) (fetch-in-chunks fetch 200 2 (range 2000)))) + (is (= 2 @peak) "Runs at most max-threads chunks at once"))) diff --git a/oracle-lib/README.md b/oracle-lib/README.md index 058c424a62..f8f251b408 100644 --- a/oracle-lib/README.md +++ b/oracle-lib/README.md @@ -30,6 +30,57 @@ To install the oracle jars for CMR: 4. In the project root directory, run `cmr install oracle-libs` which will install the oracle jars in your local maven repository. +## Connection Dials + +These settings control how many Oracle sessions CMR opens and how long requests +wait for one. They are read from environment variables when an app starts, so a +change takes effect on restart. + +| Environment variable | Default | Controls | +|---|---|---| +| `CMR_DB_MAX_POOL_SIZE` | 100 | Most connections one pool opens. Must be at least 1; the app fails to start otherwise. | +| `CMR_DB_CONNECTION_WAIT_TIMEOUT` | 600 | Seconds one connection checkout waits on a full pool before it fails. It bounds each checkout, not the whole request. | +| `CMR_PARALLEL_CHUNK_SIZE` | 200 | Concepts per chunk when metadata-db fetches a batch of concepts; each chunk is read on one connection. 0 turns chunking off, so one connection reads the whole batch. | +| `CMR_PARALLEL_CHUNK_THREADS` | 2 | Most chunks one fetch reads at once, each on its own connection. | + +The pool settings apply to every pool in a process: metadata-db, ingest and +search have one pool each (search embeds metadata-db), and bootstrap has two. +The chunk settings apply wherever metadata-db code fetches concepts: the +metadata-db app, search (for example umm_json results) and bootstrap. + +### How they combine + +- Sessions from one task: pools in the process × `CMR_DB_MAX_POOL_SIZE`. +- Sessions across CMR: add that up over every running task of every app. Keep + the total below the database's session limit, with headroom for other + clients. +- A fetch is split by provider and concept type, then into chunks of + `CMR_PARALLEL_CHUNK_SIZE`, read at most `CMR_PARALLEL_CHUNK_THREADS` at a + time. A page of 2000 granules from one provider with the defaults is 10 + chunks, 2 at a time, holding 2 connections. +- A task can run about `CMR_DB_MAX_POOL_SIZE` / `CMR_PARALLEL_CHUNK_THREADS` + large fetches at once. Further fetches wait for connections. A fetch checks + a connection out once per chunk, so under load a full pool slows requests + rather than failing them. + +### When to turn them + +- Oracle near its session limit, or slowing under bursts: lower + `CMR_DB_MAX_POOL_SIZE` on the apps with the most tasks, usually search. Extra + requests then queue inside the app rather than open more sessions. Keep + metadata-db's pool well above its concurrent saves: a save holds one + connection while it borrows another, so a small pool there deadlocks until + `CMR_DB_CONNECTION_WAIT_TIMEOUT` runs out. +- Oracle stalled with connections held for minutes: lower + `CMR_DB_CONNECTION_WAIT_TIMEOUT` so waiting requests give up rather than hold + threads and memory for up to 10 minutes. Under ordinary load it rarely + triggers, because connections free up between chunks. +- Large pages slow while the database has spare capacity: raise + `CMR_PARALLEL_CHUNK_THREADS`. Each step adds one connection per large fetch; + 10 runs every chunk of a 2000-concept fetch at once. +- `CMR_PARALLEL_CHUNK_SIZE`: smaller values mean more, shorter connection checkouts. Leave + it at 200 unless measurements say otherwise. + ## License Copyright © 2014-2021 NASA diff --git a/oracle-lib/src/cmr/oracle/connection.clj b/oracle-lib/src/cmr/oracle/connection.clj index fbbeef1375..79d413f828 100644 --- a/oracle-lib/src/cmr/oracle/connection.clj +++ b/oracle-lib/src/cmr/oracle/connection.clj @@ -23,6 +23,16 @@ {:default true :type Boolean}) +(defconfig db-max-pool-size + "Maximum number of connections in each Oracle connection pool." + {:default 100 + :type Long}) + +(defconfig db-connection-wait-timeout + "Seconds a request waits to borrow an Oracle connection from a full pool before failing." + {:default 600 + :type Long}) + (defn db-spec [connection-pool-name db-url fcf-enabled ons-config user password] {:classname "oracle.jdbc.pool.OracleDataSource" @@ -117,17 +127,22 @@ password connection-pool-name fcf-enabled - ons-config]} spec] + ons-config]} spec + max-pool-size (db-max-pool-size)] + ;; UCP only rejects a bad size on first use, after the app has started and passed health checks. + (when-not (pos? max-pool-size) + (throw (IllegalArgumentException. + (str "CMR_DB_MAX_POOL_SIZE must be at least 1, got " max-pool-size)))) (doto (PoolDataSourceFactory/getPoolDataSource) (.setConnectionFactoryClassName classname) (.setConnectionPoolName connection-pool-name) (.setUser user) (.setPassword password) (.setURL (str "jdbc:" subprotocol ":" subname)) - (.setMinPoolSize 5) - (.setMaxPoolSize 100) + (.setMinPoolSize (int (min 5 max-pool-size))) + (.setMaxPoolSize (int max-pool-size)) (.setInactiveConnectionTimeout 60) - (.setConnectionWaitTimeout 600) + (.setConnectionWaitTimeout (int (db-connection-wait-timeout))) (.setPropertyCycle 120) (.setFastConnectionFailoverEnabled fcf-enabled) (.setONSConfiguration ons-config) diff --git a/search-app/src/cmr/search/results_handlers/generics_json_results_handler.clj b/search-app/src/cmr/search/results_handlers/generics_json_results_handler.clj index 30fa52d306..841f4674e3 100644 --- a/search-app/src/cmr/search/results_handlers/generics_json_results_handler.clj +++ b/search-app/src/cmr/search/results_handlers/generics_json_results_handler.clj @@ -108,7 +108,7 @@ (defmethod results-helper/elastic-result+metadata->umm-json-item doseq-concept-type [concept-type elastic-result metadata] {:meta (results-helper/elastic-result->meta doseq-concept-type elastic-result) - :umm (json/decode metadata)}) + :umm (results-helper/encoded-json metadata)}) (defmethod er-to-qr/elastic-results->query-results [doseq-concept-type :umm-json-results] [context query elastic-results] diff --git a/search-app/src/cmr/search/results_handlers/granules_umm_json_results_handler.clj b/search-app/src/cmr/search/results_handlers/granules_umm_json_results_handler.clj index 180e012eab..e707b82eec 100644 --- a/search-app/src/cmr/search/results_handlers/granules_umm_json_results_handler.clj +++ b/search-app/src/cmr/search/results_handlers/granules_umm_json_results_handler.clj @@ -49,7 +49,7 @@ (defmethod results-helper/elastic-result+metadata->umm-json-item :granule [_concept-type elastic-result metadata] {:meta (granule-elastic-result->meta elastic-result) - :umm (json/decode metadata)}) + :umm (results-helper/encoded-json metadata)}) (defmethod elastic-results/elastic-results->query-results [:granule :umm-json-results] [context query elastic-results] diff --git a/search-app/src/cmr/search/results_handlers/services_umm_json_results_handler.clj b/search-app/src/cmr/search/results_handlers/services_umm_json_results_handler.clj index 4227fbff63..27f6a06aad 100644 --- a/search-app/src/cmr/search/results_handlers/services_umm_json_results_handler.clj +++ b/search-app/src/cmr/search/results_handlers/services_umm_json_results_handler.clj @@ -14,7 +14,7 @@ (defmethod results-helper/elastic-result+metadata->umm-json-item :service [_concept-type elastic-result metadata] {:meta (results-helper/elastic-result->meta :service elastic-result) - :umm (json/decode metadata)}) + :umm (results-helper/encoded-json metadata)}) (defmethod elastic-results/elastic-results->query-results [:service :umm-json-results] [context query elastic-results] diff --git a/search-app/src/cmr/search/results_handlers/subscriptions_umm_json_results_handler.clj b/search-app/src/cmr/search/results_handlers/subscriptions_umm_json_results_handler.clj index 8bfc5a68c8..ed28a30ae9 100644 --- a/search-app/src/cmr/search/results_handlers/subscriptions_umm_json_results_handler.clj +++ b/search-app/src/cmr/search/results_handlers/subscriptions_umm_json_results_handler.clj @@ -14,7 +14,7 @@ (defmethod results-helper/elastic-result+metadata->umm-json-item :subscription [_concept-type elastic-result metadata] {:meta (results-helper/elastic-result->meta :subscription elastic-result) - :umm (json/decode metadata)}) + :umm (results-helper/encoded-json metadata)}) (defmethod elastic-results/elastic-results->query-results [:subscription :umm-json-results] [context query elastic-results] diff --git a/search-app/src/cmr/search/results_handlers/tools_umm_json_results_handler.clj b/search-app/src/cmr/search/results_handlers/tools_umm_json_results_handler.clj index 8b6c8a9e1f..ceb0f516a7 100644 --- a/search-app/src/cmr/search/results_handlers/tools_umm_json_results_handler.clj +++ b/search-app/src/cmr/search/results_handlers/tools_umm_json_results_handler.clj @@ -14,7 +14,7 @@ (defmethod results-helper/elastic-result+metadata->umm-json-item :tool [concept-type elastic-result metadata] {:meta (results-helper/elastic-result->meta :tool elastic-result) - :umm (json/decode metadata)}) + :umm (results-helper/encoded-json metadata)}) (defmethod elastic-results/elastic-results->query-results [:tool :umm-json-results] [context query elastic-results] diff --git a/search-app/src/cmr/search/results_handlers/umm_json_results_handler.clj b/search-app/src/cmr/search/results_handlers/umm_json_results_handler.clj index 5b7af5e686..d0717240a7 100644 --- a/search-app/src/cmr/search/results_handlers/umm_json_results_handler.clj +++ b/search-app/src/cmr/search/results_handlers/umm_json_results_handler.clj @@ -53,7 +53,7 @@ (defmethod results-helper/elastic-result+metadata->umm-json-item :collection [concept-type elastic-result metadata] {:meta (collection-elastic-result->meta elastic-result) - :umm (json/decode metadata)}) + :umm (results-helper/encoded-json metadata)}) (defmethod elastic-results/elastic-results->query-results [:collection :umm-json-results] [context query elastic-results] diff --git a/search-app/src/cmr/search/results_handlers/umm_json_results_helper.clj b/search-app/src/cmr/search/results_handlers/umm_json_results_helper.clj index e7448155ab..a31c600436 100644 --- a/search-app/src/cmr/search/results_handlers/umm_json_results_helper.clj +++ b/search-app/src/cmr/search/results_handlers/umm_json_results_helper.clj @@ -1,6 +1,8 @@ (ns cmr.search.results-handlers.umm-json-results-helper "Helper functions and definitions for handling common umm-json results format." (:require + [cheshire.factory :as factory] + [cheshire.generate :as generate] [clojure.edn :as edn] [clojure.string :as string] [cmr.common.mime-types :as mt] @@ -8,7 +10,33 @@ [cmr.common.util :as util] [cmr.elastic-utils.search.es-results-to-query-results :as er-to-qr] [cmr.search.data.metadata-retrieval.metadata-cache :as metadata-cache] - [cmr.search.results-handlers.results-handler-util :as rs-util])) + [cmr.search.results-handlers.results-handler-util :as rs-util]) + (:import + (com.fasterxml.jackson.core JsonFactory JsonGenerator))) + +(deftype EncodedJson [^String json]) + +(def ^:private ^JsonFactory parser-factory + "Cheshire's default JSON factory settings, with field names canonicalized so the same UMM keys + aren't allocated again for every document." + (factory/make-json-factory {:canonicalize-field-names true})) + +(generate/add-encoder + EncodedJson + (fn [^EncodedJson value ^JsonGenerator generator] + ;; Copied token by token rather than written raw so stored native documents come out compact. + (with-open [parser (.createParser parser-factory ^String (.json value))] + (if (.nextToken parser) + (.copyCurrentStructure generator parser) + ;; Blank metadata decoded to nil before, so keep writing null for it. + (.writeNull generator))))) + +(defn encoded-json + "Wraps a JSON string so cheshire writes it into a response without decoding it into Clojure data. + Returns nil for nil, as decoding did." + [^String json] + (when json + (->EncodedJson json))) (def meta-fields "Defines the fields in elastic search we retrieve to populate the meta fields in the response." diff --git a/search-app/src/cmr/search/results_handlers/variables_umm_json_results_handler.clj b/search-app/src/cmr/search/results_handlers/variables_umm_json_results_handler.clj index b071fdeb6c..23c9c4a72e 100644 --- a/search-app/src/cmr/search/results_handlers/variables_umm_json_results_handler.clj +++ b/search-app/src/cmr/search/results_handlers/variables_umm_json_results_handler.clj @@ -26,7 +26,7 @@ (defmethod results-helper/elastic-result+metadata->umm-json-item :variable [_concept-type elastic-result metadata] (let [base-result-item {:meta (results-helper/elastic-result->meta :variable elastic-result) - :umm (json/decode metadata)} + :umm (results-helper/encoded-json metadata)} associated-concepts (elastic-result->associated-concepts elastic-result)] (if associated-concepts (assoc base-result-item :associations associated-concepts) diff --git a/search-app/test/cmr/search/test/unit/results_handlers/umm_json_results_helper.clj b/search-app/test/cmr/search/test/unit/results_handlers/umm_json_results_helper.clj new file mode 100644 index 0000000000..d4b9edf2e5 --- /dev/null +++ b/search-app/test/cmr/search/test/unit/results_handlers/umm_json_results_helper.clj @@ -0,0 +1,16 @@ +(ns cmr.search.test.unit.results-handlers.umm-json-results-helper + (:require + [cheshire.core :as json] + [clojure.test :refer [deftest is]] + [cmr.search.results-handlers.umm-json-results-helper :as results-helper])) + +(deftest encoded-json-test + (let [umm (str "{\n \"GranuleUR\": \"caf\\u00e9 \\\"G1\\\"\",\n" + " \"Size\": 1.50E-7,\n" + " \"Count\": 12345678901234567890,\n" + " \"Flags\": [true, null, {\"Empty\": []}]\n}")] + (is (= (json/generate-string {:umm (json/decode umm)}) + (json/generate-string {:umm (results-helper/encoded-json umm)})) + "Writes the same compact JSON as decoding and re-encoding") + (doseq [blank [nil "" " \n"]] + (is (= "{\"umm\":null}" (json/generate-string {:umm (results-helper/encoded-json blank)})))))) diff --git a/system-int-test/test/cmr/system_int_test/search/misc/generic_association_test.clj b/system-int-test/test/cmr/system_int_test/search/misc/generic_association_test.clj index 0d42087f6e..034b5ddee6 100644 --- a/system-int-test/test/cmr/system_int_test/search/misc/generic_association_test.clj +++ b/system-int-test/test/cmr/system_int_test/search/misc/generic_association_test.clj @@ -223,9 +223,10 @@ ;; Search for the tool, it should return the association tl1-search-result (get-associations-and-details "tools.umm_json" "native_id=tl1" :grids true) - ;;Update the tool and the grid, search for the grid and the tool, it should return the association. + ;; Update the tool and the grid; their new revisions don't carry the association pinned to the old ones. _ (gen-util/ingest-generic-document nil "PROV1" native-id :grid grid-doc :post) _ (tool-util/ingest-tool-with-attrs {:native-id "tl1" :Name "tool1"}) + _ (index/wait-until-indexed) grid-search-result-update (get-associations-and-details "grids.json" "name=Grid-A7-v1" :tools false) tl1-search-result-update (get-associations-and-details "tools.umm_json" "native_id=tl1" :grids true) @@ -260,16 +261,18 @@ ;; Search for the grid returns the tl1 as generic association (is (= [tl1-concept-id] - (:associations grid-search-result) - (:associations grid-search-result-update))) + (:associations grid-search-result))) (is (= [{:concept_id tl1-concept-id :revision_id tl1-revision-id}] ;; The grid is being searched from the .json endpoint which uses snake case assocation-details - (:association_details grid-search-result) - (:association_details grid-search-result-update))) + (:association_details grid-search-result))) ;; Search for the tool returns the grid as generic association (is (= [grid-concept-id] - (:associations tl1-search-result) + (:associations tl1-search-result))) + + ;; The updated grid and tool don't return the association + (is (= nil + (:associations grid-search-result-update) (:associations tl1-search-result-update))) ;; Dissociation of the association is successful