lkuchars commented on code in PR #10214:
URL: https://github.com/apache/nifi/pull/10214#discussion_r2290855229


##########
nifi-extension-bundles/nifi-protobuf-bundle/nifi-protobuf-services/src/main/java/org/apache/nifi/services/protobuf/ProtobufSchemaCompiler.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.services.protobuf;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.squareup.wire.schema.CoreLoaderKt;
+import com.squareup.wire.schema.Location;
+import com.squareup.wire.schema.Schema;
+import com.squareup.wire.schema.SchemaLoader;
+import org.apache.commons.io.FileUtils;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.schemaregistry.services.SchemaDefinition;
+import org.apache.nifi.serialization.record.SchemaIdentifier;
+
+import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Handles Protocol Buffer schema compilation, caching, and temporary 
directory operations.
+ * This class is responsible for compiling schema definitions into Wire Schema 
objects,
+ * managing a cache of compiled schemas, and handling temporary directory 
operations
+ * required during the compilation process.
+ */
+final class ProtobufSchemaCompiler {
+
+    private static final List<Location> STANDARD_PROTOBUF_LOCATIONS = 
Arrays.asList(
+        Location.get(CoreLoaderKt.WIRE_RUNTIME_JAR, 
"google/protobuf/any.proto"),
+        Location.get(CoreLoaderKt.WIRE_RUNTIME_JAR, 
"google/protobuf/duration.proto"),
+        Location.get(CoreLoaderKt.WIRE_RUNTIME_JAR, 
"google/protobuf/empty.proto"),
+        Location.get(CoreLoaderKt.WIRE_RUNTIME_JAR, 
"google/protobuf/struct.proto"),
+        Location.get(CoreLoaderKt.WIRE_RUNTIME_JAR, 
"google/protobuf/timestamp.proto"),
+        Location.get(CoreLoaderKt.WIRE_RUNTIME_JAR, 
"google/protobuf/wrappers.proto")
+    );
+    private static final int CACHE_EXPIRE_HOURS = 1;
+    private static final int COMPILED_SCHEMAS_CACHE_SIZE = 200;
+
+    private final Cache<SchemaIdentifier, Schema> compiledSchemaCache;
+    private final ComponentLog logger;
+
+    /**
+     * Creates a new ProtobufSchemaCompiler with default cache settings.
+     *
+     * @param logger the component logger for logging compilation activities
+     */
+    public ProtobufSchemaCompiler(final ComponentLog logger) {
+        this.logger = logger;
+        this.compiledSchemaCache = Caffeine.newBuilder()
+            .expireAfterAccess(CACHE_EXPIRE_HOURS, TimeUnit.HOURS)
+            .maximumSize(COMPILED_SCHEMAS_CACHE_SIZE)
+            .build();
+    }
+
+    /**
+     * Compiles a schema definition or retrieves it from cache.
+     *
+     * @param schemaDefinition the schema definition to compile
+     * @return the compiled Schema
+     */
+    public Schema compileOrGetFromCache(final SchemaDefinition 
schemaDefinition) {
+        return compiledSchemaCache.get(schemaDefinition.getIdentifier(),
+            identifier -> {
+                try {
+                    return compileSchemaDefinition(schemaDefinition);
+                } catch (final IOException e) {
+                    throw new RuntimeException("Could not compile schema for 
identifier: " + identifier, e);
+                }
+            });
+    }
+
+    /**
+     * Invalidates all cached schemas.
+     */
+    public void invalidateCache() {
+        if (compiledSchemaCache != null) {
+            compiledSchemaCache.invalidateAll();
+        }
+    }
+
+    /**
+     * Compiles a SchemaDefinition structure into a Schema using the wire 
library.
+     * Creates a temporary directory structure that mirrors the package 
structure and
+     * places all schemas in their appropriate directories.
+     *
+     * @param schemaDefinition the main schema definition to compile
+     * @return the compiled Schema
+     * @throws IOException if unable to create temporary files or compile 
schema
+     */
+    private Schema compileSchemaDefinition(final SchemaDefinition 
schemaDefinition) throws IOException {
+        logger.debug("Starting schema compilation for identifier: {}", 
schemaDefinition.getIdentifier());
+
+        // Validate that all schema identifiers end with .proto extension
+        validateSchemaDefinitionIdentifiers(schemaDefinition, true);
+
+        return executeWithTemporaryDirectory(tempDir -> {
+            try {
+                // Process main schema definition
+                writeSchemaToTempDirectory(tempDir, schemaDefinition);
+
+                // Process all referenced schemas recursively
+                processSchemaReferences(tempDir, 
schemaDefinition.getReferences());
+
+                // Create and configure schema loader
+                final Schema compiledSchema = createAndLoadSchema(tempDir);
+                logger.debug("Successfully compiled schema for identifier: 
{}", schemaDefinition.getIdentifier());
+                return compiledSchema;
+
+            } catch (final Exception e) {
+                throw new RuntimeException("Failed to compile Protobuf schema 
for identifier: " + schemaDefinition.getIdentifier(), e);
+            }
+        });
+    }
+
+    /**
+     * Executes a function with a temporary directory, ensuring proper cleanup.
+     *
+     * @param function the function to execute with the temporary directory
+     * @return the result of the function
+     * @throws IOException if unable to create or manage temporary directory
+     */
+    private <T> T executeWithTemporaryDirectory(final 
WithTemporaryDirectory<T> function) throws IOException {
+        final Path tempDir = Files.createTempDirectory("nifi-protobuf-schema");

Review Comment:
   IMO, both options are not needed. If I had to pick one, I'd go with in 
memory filesystem, instead of going with error prone, own implementaiton of 
SchemaLoader. The short write to temp file once every hour or so is not going 
to affect anyting. If @exceptionfactory is ok with introducing jims, I can go 
with that. Otherwise, IMO I'll just change the temp folder suffix to scope it 
to the component, and lets go with it?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to