Delegate System

Overview

The delegate system enables the use of custom code to customize the image server's behavior. It can be utilized in one of two ways:

  1. Using the Ruby delegate script. This method is designed for ease of use. Ruby is generally easy to work with, and only a small amount of code is needed to support most use cases.
  2. Using a Java delegate. This is an alternative to the delegate script for users who require faster startup time or are more comfortable with Java than Ruby.

Delegate Script

The delegate script is a file containing a delegate class written in Ruby. The class is instantiated per-request, early in the request cycle, and disposed of at the end of the request cycle. At various points in the request cycle, its methods are called by the application to obtain information needed to service the request.

Before any other methods are called, the application will set the request context, which is a hash of request properties with perhaps some other helpful information mixed in. See the documentation of the context attribute (attr_accessor :context) in the sample delegate script file for information about the keys that may be present in the context hash.

You can also use a statement like context.each{ |k,v| puts "#{k}: #{v}" } in any method to print the context to the console.

The delegate script is reloaded whenever the script file changes. Be aware, though, that code that has already been loaded into the JRuby runtime cannot be unloaded. For example, when a class is changed, the new version will replace the old version; but constants within the class cannot be redefined.

Generally, neither the context, method arguments, nor return values are sanitized or validated. Be careful to write defensive, injection-safe code.

Getting Started

The delegate script is disabled by default. To enable it, follow these steps:

  1. Copy the sample delegate script, delegates.rb.sample, included in the distribution, to delegates.rb.
  2. Reference it from the delegate_script.pathname configuration option.
  3. Set delegate_script.enabled to true.

Migrating

From the 4.1 Script to the 5.0 Script

In version 5.0, a new method named pre_authorize() was added. In many cases, the authorize() implementation can simply be moved into this new method, unless it contains logic that depends on information read from the underlying source image. See the sample delegate script, as well as the Access Control section, for more information.

From the 4.0 Script to the 4.1 Script

In version 4.1, the authorized?() and redirect() methods were merged into authorize(). See the documentation in the sample delegate script file for more information.

From the 3.x Script to the 4.0 Script

See the 4.0 user manual.

Gems

JRuby can use most Ruby gems, except those that have been built with native extensions. To import a gem, use a require statement:

require 'mygem'

require searches for gems based on the $GEM_PATH environment variable, falling back to $GEM_HOME if that is not defined. If JRuby fails to find your gem, check your $GEM_PATH. If you installed the gem using gem install, check the output of gem env (particularly the "gem paths" section) to see where it might have been installed, and ensure that those locations are present in $GEM_PATH.

Calling Java Code

This example uses URLConnection, which is part of the JDK, to execute an HTTP request, as an alternative to other examples which use Ruby's Net::HTTP library.

require 'java'

java_import java.net.HttpURLConnection
java_import java.net.URL
java_import java.io.BufferedReader
java_import java.io.FileNotFoundException
java_import java.io.InputStreamReader
java_import java.util.stream.Collectors

class CustomDelegate
  def do_something
    url = URL.new('http://example.org/')
    conn, is, reader = nil
    begin
      conn = url.openConnection
      conn.setRequestMethod 'GET'
      conn.setReadTimeout 30 * 1000
      conn.connect
      is = conn.getInputStream
      status = conn.getResponseCode

      if status == 200
        content_type = conn.getHeaderField 'Content-Type'
        if content_type.include? 'text/plain'
          reader = BufferedReader.new(InputStreamReader.new(is))
          entity = reader.lines.collect(Collectors.joining("\n"))
          puts entity
        else
          raise IOError, "Unexpected Content-Type: #{content_type}"
        end
      else
        raise IOError, "Unexpected status: #{status}"
      end
    rescue FileNotFoundException => e
      return nil
    rescue => e
      Java::edu.illinois.library.cantaloupe.delegate.Logger.error("#{e}", e)
    ensure
      reader&.close
      is&.close
      conn&.disconnect
    end
  end
end

See also: CallingJavaFromJRuby

The whole JDK is at your fingertips, and there's nothing to stop you from using third-party JARs and accessing their API from JRuby. Be careful, though, as JARs may contain code that conflicts with the application's dependencies—different versions of the same library, for example.

Improving Efficiency

Several delegate methods will be called over the course of a single request, and making them as efficient as possible will improve response times. A couple of ways to improve efficiency are:

Sharing Information

Some methods may need to do similar work, which may be expensive. To avoid having to do it twice, a useful technique is to cache the first result. So, rather than doing this:

class CustomDelegate
  def method1(options = {})
    # perform an expensive query and return the result
  end

  def method2(options = {})
    # perform the same expensive query and return the result
  end
end

You could do this:

class CustomDelegate
  def method1(options = {})
    result = perform_expensive_query
  end

  def method2(options = {})
    result = perform_expensive_query
  end

  # Performs an expensive query only once, caching the result.
  def perform_expensive_query
    unless @result
      # perform the query
      @result = ... # save the result in an instance variable
    end
    @result
  end
end

Connection Pooling

Most HTTP clients maintain an internal connection pool, but JDBC adapters do not. When accessing a database via JDBC, consider using a connection pool to improve performance. As of now, there is no "official" provision for this, but some options include:

  1. Use the built-in HikariCP pool used by JdbcSource and JdbcCache, noting that HikariCP is not part of the delegate script contract and may change or go away at some point (see here for an example that may or may not work);
  2. Supply a third-party connection pooling library as a JAR;
  3. Write your own connection pool

Logging

Delegate methods may access a logger that writes to the application log:

require 'java'

logger = Java::edu.illinois.library.cantaloupe.delegate.Logger
logger.trace 'Hello world'
logger.debug 'Hello world'
logger.info 'Hello world'
logger.warn 'Hello world'
logger.error 'Hello world'

Error stack traces may also be logged:

require 'java'

logger = Java::edu.illinois.library.cantaloupe.delegate.Logger

begin
  raise 'Goodbye world'
rescue => e
  logger.error("#{e}", e)
end

Testing Delegate Methods

Delegate methods can be tested by creating an instance of the CustomDelegate class, setting its context to be similar to what the application would set it to, and calling a method:

# This file is named `test.rb`, in the same folder as `delegates.rb`
require './delegates'

obj = CustomDelegate.new
obj.context = {
  'identifier' => 'identifier-to-test',
  'client_ip' => '127.0.0.1',
  'request_headers' => ...
}

puts obj.filesystemsource_pathname

This script can then be run on the command line with a command like: ruby test.rb.

The ruby command will normally invoke the standard ("MRI") Ruby interpreter, and not the JRuby interpreter. While they mostly work pretty similar, gems with platform-native extensions won't work in JRuby. Consider installing a standalone JRuby interpreter and test with that instead. (A tool like RVM can make it easy to switch between different Ruby environments.)


Java Delegate

The Java delegate system was introduced in version 5.0. It relies on a delegate class that is very similar to the one used in the delegate script system, but instead is written in Java (or some other JVM language), compiled, and packed into a JAR file. Cantaloupe relies on the JDK's ServiceLoader system to auto-discover the delegate class and then instantiate and use it in the same way its Ruby counterpart is used.

Unlike the delegate script, a sample Java delegate is not bundled with the application. Instead, refer to the sample Java delegate, which provides a minimal working example.

Links