|
| 1 | +/* |
| 2 | + * Copyright (c) 2010-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. |
| 3 | + */ |
| 4 | +package com.marklogic.client.datamovement.filter; |
| 5 | + |
| 6 | +import com.marklogic.client.datamovement.DocumentWriteSetFilter; |
| 7 | +import com.marklogic.client.document.DocumentWriteOperation; |
| 8 | +import com.marklogic.client.document.DocumentWriteSet; |
| 9 | +import com.marklogic.client.impl.DocumentWriteOperationImpl; |
| 10 | +import com.marklogic.client.impl.HandleAccessor; |
| 11 | +import com.marklogic.client.io.BaseHandle; |
| 12 | +import com.marklogic.client.io.DocumentMetadataHandle; |
| 13 | +import com.marklogic.client.io.Format; |
| 14 | +import net.openhft.hashing.LongHashFunction; |
| 15 | +import org.erdtman.jcs.JsonCanonicalizer; |
| 16 | +import org.slf4j.Logger; |
| 17 | +import org.slf4j.LoggerFactory; |
| 18 | + |
| 19 | +import java.io.IOException; |
| 20 | +import java.nio.charset.StandardCharsets; |
| 21 | +import java.util.ArrayList; |
| 22 | +import java.util.List; |
| 23 | +import java.util.function.Consumer; |
| 24 | +import java.util.function.Function; |
| 25 | + |
| 26 | +/** |
| 27 | + * A DocumentWriteSetFilter that skips writing documents whose content has not changed since the last write |
| 28 | + * based on a hash value stored in a MarkLogic field. |
| 29 | + * |
| 30 | + * @since 8.1.0 |
| 31 | + */ |
| 32 | +public abstract class IncrementalWriteFilter implements DocumentWriteSetFilter { |
| 33 | + |
| 34 | + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); |
| 35 | + |
| 36 | + public static Builder newBuilder() { |
| 37 | + return new Builder(); |
| 38 | + } |
| 39 | + |
| 40 | + public static class Builder { |
| 41 | + |
| 42 | + private String fieldName = "incrementalWriteHash"; |
| 43 | + private boolean canonicalizeJson = true; |
| 44 | + private boolean useEvalQuery = false; |
| 45 | + private Consumer<DocumentWriteOperation[]> skippedDocumentsConsumer; |
| 46 | + |
| 47 | + /** |
| 48 | + * @param fieldName the name of the MarkLogic field that will hold the hash value; defaults to "incrementalWriteHash". |
| 49 | + */ |
| 50 | + public Builder fieldName(String fieldName) { |
| 51 | + this.fieldName = fieldName; |
| 52 | + return this; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * @param canonicalizeJson whether to canonicalize JSON content before hashing; defaults to true. |
| 57 | + * Delegates to https://github.com/erdtman/java-json-canonicalization for canonicalization. |
| 58 | + */ |
| 59 | + public Builder canonicalizeJson(boolean canonicalizeJson) { |
| 60 | + this.canonicalizeJson = canonicalizeJson; |
| 61 | + return this; |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * @param useEvalQuery if true, evaluate server-side JavaScript instead of an Optic query for retrieving hash values; defaults to false. |
| 66 | + */ |
| 67 | + public Builder useEvalQuery(boolean useEvalQuery) { |
| 68 | + this.useEvalQuery = useEvalQuery; |
| 69 | + return this; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * @param skippedDocumentsConsumer a consumer that will be called with any documents in a batch that were skipped because their content had not changed. |
| 74 | + */ |
| 75 | + public Builder onDocumentsSkipped(Consumer<DocumentWriteOperation[]> skippedDocumentsConsumer) { |
| 76 | + this.skippedDocumentsConsumer = skippedDocumentsConsumer; |
| 77 | + return this; |
| 78 | + } |
| 79 | + |
| 80 | + public IncrementalWriteFilter build() { |
| 81 | + if (useEvalQuery) { |
| 82 | + return new IncrementalWriteEvalFilter(fieldName, canonicalizeJson, skippedDocumentsConsumer); |
| 83 | + } |
| 84 | + return new IncrementalWriteOpticFilter(fieldName, canonicalizeJson, skippedDocumentsConsumer); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + protected final String fieldName; |
| 89 | + private final boolean canonicalizeJson; |
| 90 | + private final Consumer<DocumentWriteOperation[]> skippedDocumentsConsumer; |
| 91 | + |
| 92 | + // Hardcoding this for now, with a good general purpose hashing function. |
| 93 | + // See https://xxhash.com for benchmarks. |
| 94 | + private final LongHashFunction hashFunction = LongHashFunction.xx3(); |
| 95 | + |
| 96 | + public IncrementalWriteFilter(String fieldName, boolean canonicalizeJson, Consumer<DocumentWriteOperation[]> skippedDocumentsConsumer) { |
| 97 | + this.fieldName = fieldName; |
| 98 | + this.canonicalizeJson = canonicalizeJson; |
| 99 | + this.skippedDocumentsConsumer = skippedDocumentsConsumer; |
| 100 | + } |
| 101 | + |
| 102 | + protected final DocumentWriteSet filterDocuments(Context context, Function<String, String> hashRetriever) { |
| 103 | + final DocumentWriteSet newWriteSet = context.getDatabaseClient().newDocumentManager().newWriteSet(); |
| 104 | + final List<DocumentWriteOperation> skippedDocuments = new ArrayList<>(); |
| 105 | + |
| 106 | + for (DocumentWriteOperation doc : context.getDocumentWriteSet()) { |
| 107 | + if (!DocumentWriteOperation.OperationType.DOCUMENT_WRITE.equals(doc.getOperationType())) { |
| 108 | + newWriteSet.add(doc); |
| 109 | + continue; |
| 110 | + } |
| 111 | + |
| 112 | + final String contentHash = serializeContent(doc); |
| 113 | + final String existingHash = hashRetriever.apply(doc.getUri()); |
| 114 | + if (logger.isTraceEnabled()) { |
| 115 | + logger.trace("URI: {}, existing Hash: {}, new Hash: {}", doc.getUri(), existingHash, contentHash); |
| 116 | + } |
| 117 | + |
| 118 | + if (existingHash != null) { |
| 119 | + if (!existingHash.equals(contentHash)) { |
| 120 | + newWriteSet.add(addHashToMetadata(doc, fieldName, contentHash)); |
| 121 | + } else if (skippedDocumentsConsumer != null) { |
| 122 | + skippedDocuments.add(doc); |
| 123 | + } else { |
| 124 | + // No consumer, so skip the document silently. |
| 125 | + } |
| 126 | + } else { |
| 127 | + newWriteSet.add(addHashToMetadata(doc, fieldName, contentHash)); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + if (!skippedDocuments.isEmpty()) { |
| 132 | + skippedDocumentsConsumer.accept(skippedDocuments.toArray(new DocumentWriteOperation[0])); |
| 133 | + } |
| 134 | + |
| 135 | + return newWriteSet; |
| 136 | + } |
| 137 | + |
| 138 | + private String serializeContent(DocumentWriteOperation doc) { |
| 139 | + String content = HandleAccessor.contentAsString(doc.getContent()); |
| 140 | + |
| 141 | + Format format = null; |
| 142 | + if (doc.getContent() instanceof BaseHandle<?, ?> baseHandle) { |
| 143 | + format = baseHandle.getFormat(); |
| 144 | + } |
| 145 | + |
| 146 | + if (canonicalizeJson && (Format.JSON.equals(format) || isPossiblyJsonContent(content))) { |
| 147 | + JsonCanonicalizer jc; |
| 148 | + try { |
| 149 | + jc = new JsonCanonicalizer(content); |
| 150 | + return jc.getEncodedString(); |
| 151 | + } catch (IOException e) { |
| 152 | + // Going to improve this in the next PR, as I think we can throw an exception if Format = JSON. |
| 153 | + logger.warn("Unable to canonicalize JSON content for URI {}, using original content for hashing; cause: {}", |
| 154 | + doc.getUri(), e.getMessage()); |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + return content; |
| 159 | + } |
| 160 | + |
| 161 | + private boolean isPossiblyJsonContent(String content) { |
| 162 | + // This isn't 100% reliable, as the content could be text that just happens to start with { or [, and so |
| 163 | + // we'll still need to catch an exception if we try to canonicalize non-JSON content. |
| 164 | + String trimmed = content.trim(); |
| 165 | + return trimmed.startsWith("{") || trimmed.startsWith("["); |
| 166 | + } |
| 167 | + |
| 168 | + private String computeHash(String content) { |
| 169 | + byte[] bytes = content.getBytes(StandardCharsets.UTF_8); |
| 170 | + long hash = hashFunction.hashBytes(bytes); |
| 171 | + return Long.toHexString(hash); |
| 172 | + } |
| 173 | + |
| 174 | + protected static DocumentWriteOperation addHashToMetadata(DocumentWriteOperation op, String fieldName, String hash) { |
| 175 | + DocumentMetadataHandle newMetadata = new DocumentMetadataHandle(); |
| 176 | + if (op.getMetadata() != null) { |
| 177 | + DocumentMetadataHandle originalMetadata = (DocumentMetadataHandle) op.getMetadata(); |
| 178 | + newMetadata.setPermissions(originalMetadata.getPermissions()); |
| 179 | + newMetadata.setCollections(originalMetadata.getCollections()); |
| 180 | + newMetadata.setQuality(originalMetadata.getQuality()); |
| 181 | + newMetadata.setProperties(originalMetadata.getProperties()); |
| 182 | + newMetadata.getMetadataValues().putAll(originalMetadata.getMetadataValues()); |
| 183 | + } |
| 184 | + newMetadata.getMetadataValues().put(fieldName, hash); |
| 185 | + return new DocumentWriteOperationImpl(op.getUri(), newMetadata, op.getContent(), op.getTemporalDocumentURI()); |
| 186 | + } |
| 187 | +} |
0 commit comments