|
| 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 com.marklogic.client.io.marker.AbstractWriteHandle; |
| 15 | +import net.openhft.hashing.LongHashFunction; |
| 16 | +import org.erdtman.jcs.JsonCanonicalizer; |
| 17 | +import org.slf4j.Logger; |
| 18 | +import org.slf4j.LoggerFactory; |
| 19 | + |
| 20 | +import java.io.IOException; |
| 21 | +import java.nio.charset.StandardCharsets; |
| 22 | +import java.util.ArrayList; |
| 23 | +import java.util.List; |
| 24 | +import java.util.function.Consumer; |
| 25 | +import java.util.function.Function; |
| 26 | + |
| 27 | +/** |
| 28 | + * A DocumentWriteSetFilter that skips writing documents whose content has not changed since the last write |
| 29 | + * based on a hash value stored in a MarkLogic field. |
| 30 | + * |
| 31 | + * @since 8.1.0 |
| 32 | + */ |
| 33 | +public abstract class IncrementalWriteFilter implements DocumentWriteSetFilter { |
| 34 | + |
| 35 | + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); |
| 36 | + |
| 37 | + public static Builder newBuilder() { |
| 38 | + return new Builder(); |
| 39 | + } |
| 40 | + |
| 41 | + public static class Builder { |
| 42 | + |
| 43 | + private String fieldName = "incrementalWriteHash"; |
| 44 | + private boolean canonicalizeJson = true; |
| 45 | + private boolean useEvalQuery = false; |
| 46 | + private Consumer<DocumentWriteOperation[]> skippedDocumentsConsumer; |
| 47 | + |
| 48 | + /** |
| 49 | + * @param fieldName the name of the MarkLogic field that will hold the hash value; defaults to "incrementalWriteHash". |
| 50 | + */ |
| 51 | + public Builder fieldName(String fieldName) { |
| 52 | + this.fieldName = fieldName; |
| 53 | + return this; |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * @param canonicalizeJson whether to canonicalize JSON content before hashing; defaults to true. |
| 58 | + * Delegates to https://github.com/erdtman/java-json-canonicalization for canonicalization. |
| 59 | + */ |
| 60 | + public Builder canonicalizeJson(boolean canonicalizeJson) { |
| 61 | + this.canonicalizeJson = canonicalizeJson; |
| 62 | + return this; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * @param useEvalQuery if true, evaluate server-side JavaScript instead of an Optic query for retrieving hash values; defaults to false. |
| 67 | + */ |
| 68 | + public Builder useEvalQuery(boolean useEvalQuery) { |
| 69 | + this.useEvalQuery = useEvalQuery; |
| 70 | + return this; |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * @param skippedDocumentsConsumer a consumer that will be called with any documents in a batch that were skipped because their content had not changed. |
| 75 | + */ |
| 76 | + public Builder onDocumentsSkipped(Consumer<DocumentWriteOperation[]> skippedDocumentsConsumer) { |
| 77 | + this.skippedDocumentsConsumer = skippedDocumentsConsumer; |
| 78 | + return this; |
| 79 | + } |
| 80 | + |
| 81 | + public IncrementalWriteFilter build() { |
| 82 | + if (useEvalQuery) { |
| 83 | + return new IncrementalWriteEvalFilter(fieldName, canonicalizeJson, skippedDocumentsConsumer); |
| 84 | + } |
| 85 | + return new IncrementalWriteOpticFilter(fieldName, canonicalizeJson, skippedDocumentsConsumer); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + protected final String fieldName; |
| 90 | + private final boolean canonicalizeJson; |
| 91 | + private final Consumer<DocumentWriteOperation[]> skippedDocumentsConsumer; |
| 92 | + |
| 93 | + // Hardcoding this for now, with a good general purpose hashing function. |
| 94 | + // See https://xxhash.com for benchmarks. |
| 95 | + private final LongHashFunction hashFunction = LongHashFunction.xx3(); |
| 96 | + |
| 97 | + public IncrementalWriteFilter(String fieldName, boolean canonicalizeJson, Consumer<DocumentWriteOperation[]> skippedDocumentsConsumer) { |
| 98 | + this.fieldName = fieldName; |
| 99 | + this.canonicalizeJson = canonicalizeJson; |
| 100 | + this.skippedDocumentsConsumer = skippedDocumentsConsumer; |
| 101 | + } |
| 102 | + |
| 103 | + protected final DocumentWriteSet filterDocuments(Context context, Function<String, String> hashRetriever) { |
| 104 | + final DocumentWriteSet newWriteSet = context.getDatabaseClient().newDocumentManager().newWriteSet(); |
| 105 | + final List<DocumentWriteOperation> skippedDocuments = new ArrayList<>(); |
| 106 | + |
| 107 | + for (DocumentWriteOperation doc : context.getDocumentWriteSet()) { |
| 108 | + if (!DocumentWriteOperation.OperationType.DOCUMENT_WRITE.equals(doc.getOperationType())) { |
| 109 | + newWriteSet.add(doc); |
| 110 | + continue; |
| 111 | + } |
| 112 | + |
| 113 | + final String content = serializeContent(doc.getContent()); |
| 114 | + final String contentHash = computeHash(content); |
| 115 | + final String existingHash = hashRetriever.apply(doc.getUri()); |
| 116 | + if (logger.isTraceEnabled()) { |
| 117 | + logger.trace("URI: {}, existing Hash: {}, new Hash: {}", doc.getUri(), existingHash, contentHash); |
| 118 | + } |
| 119 | + |
| 120 | + if (existingHash != null) { |
| 121 | + if (!existingHash.equals(contentHash)) { |
| 122 | + newWriteSet.add(addHashToMetadata(doc, fieldName, contentHash)); |
| 123 | + } else if (skippedDocumentsConsumer != null) { |
| 124 | + skippedDocuments.add(doc); |
| 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(AbstractWriteHandle contentHandle) { |
| 139 | + String content = HandleAccessor.contentAsString(contentHandle); |
| 140 | + |
| 141 | + Format format = null; |
| 142 | + if (contentHandle instanceof BaseHandle<?, ?> baseHandle) { |
| 143 | + format = baseHandle.getFormat(); |
| 144 | + } |
| 145 | + |
| 146 | + if (canonicalizeJson && (Format.JSON.equals(format) || content.startsWith("{"))) { |
| 147 | + JsonCanonicalizer jc; |
| 148 | + try { |
| 149 | + jc = new JsonCanonicalizer(content); |
| 150 | + } catch (IOException e) { |
| 151 | + throw new RuntimeException("Unable to parse JSON content, cause: " + e.getMessage(), e); |
| 152 | + } |
| 153 | + return jc.getEncodedString(); |
| 154 | + } |
| 155 | + |
| 156 | + return content; |
| 157 | + } |
| 158 | + |
| 159 | + private String computeHash(String content) { |
| 160 | + byte[] bytes = content.getBytes(StandardCharsets.UTF_8); |
| 161 | + long hash = hashFunction.hashBytes(bytes); |
| 162 | + return Long.toHexString(hash); |
| 163 | + } |
| 164 | + |
| 165 | + protected static DocumentWriteOperation addHashToMetadata(DocumentWriteOperation op, String fieldName, String hash) { |
| 166 | + DocumentMetadataHandle newMetadata = new DocumentMetadataHandle(); |
| 167 | + if (op.getMetadata() != null) { |
| 168 | + DocumentMetadataHandle originalMetadata = (DocumentMetadataHandle) op.getMetadata(); |
| 169 | + newMetadata.setPermissions(originalMetadata.getPermissions()); |
| 170 | + newMetadata.setCollections(originalMetadata.getCollections()); |
| 171 | + newMetadata.setQuality(originalMetadata.getQuality()); |
| 172 | + newMetadata.setProperties(originalMetadata.getProperties()); |
| 173 | + newMetadata.getMetadataValues().putAll(originalMetadata.getMetadataValues()); |
| 174 | + } |
| 175 | + newMetadata.getMetadataValues().put(fieldName, hash); |
| 176 | + return new DocumentWriteOperationImpl(op.getUri(), newMetadata, op.getContent(), op.getTemporalDocumentURI()); |
| 177 | + } |
| 178 | +} |
0 commit comments