PageRenderTime 38ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/digdag-core/src/main/java/io/digdag/core/plugin/DynamicPluginLoader.java

https://gitlab.com/CORP-RESELLER/digdag
Java | 78 lines | 71 code | 7 blank | 0 comment | 0 complexity | e407737ae365e393a80cd952bd561c6d MD5 | raw file
  1. package io.digdag.core.plugin;
  2. import java.util.function.Function;
  3. import java.util.concurrent.TimeUnit;
  4. import java.util.concurrent.ExecutionException;
  5. import com.google.common.collect.ImmutableList;
  6. import com.google.common.util.concurrent.UncheckedExecutionException;
  7. import com.google.common.base.Throwables;
  8. import com.google.common.cache.Cache;
  9. import com.google.common.cache.CacheBuilder;
  10. import com.google.inject.Inject;
  11. import com.google.inject.Module;
  12. import com.google.inject.Injector;
  13. import com.google.inject.Guice;
  14. import com.google.inject.Stage;
  15. import io.digdag.spi.Plugin;
  16. public class DynamicPluginLoader<R>
  17. {
  18. public static <R> DynamicPluginLoader<R> build(
  19. PluginLoader loader,
  20. Module restrictInjectModule,
  21. Function<PluginSet.WithInjector, R> cacheBuilder,
  22. int maxCacheSize)
  23. {
  24. return new DynamicPluginLoader<>(
  25. loader, restrictInjectModule,
  26. cacheBuilder, maxCacheSize);
  27. }
  28. private final PluginLoader loader;
  29. private final Injector injector;
  30. private final Function<PluginSet.WithInjector, R> cacheBuilder;
  31. private final Cache<Spec, R> cache;
  32. private DynamicPluginLoader(
  33. PluginLoader loader,
  34. Module restrictInjectModule,
  35. Function<PluginSet.WithInjector, R> cacheBuilder,
  36. int maxCacheSize)
  37. {
  38. this.loader = loader;
  39. this.injector = buildRestrictedInjector(restrictInjectModule);
  40. this.cacheBuilder = cacheBuilder;
  41. this.cache = CacheBuilder.newBuilder()
  42. .maximumSize(maxCacheSize)
  43. .expireAfterWrite(10, TimeUnit.MINUTES)
  44. .build();
  45. }
  46. public R load(Spec spec)
  47. {
  48. try {
  49. return cache.get(spec, () -> loadCache(spec));
  50. }
  51. catch (UncheckedExecutionException ex) {
  52. throw Throwables.propagate(ex.getCause());
  53. }
  54. catch (ExecutionException ex) {
  55. throw Throwables.propagate(ex.getCause());
  56. }
  57. }
  58. private R loadCache(Spec spec)
  59. {
  60. PluginSet plugins = loader.load(spec);
  61. return cacheBuilder.apply(plugins.withInjector(injector));
  62. }
  63. private static Injector buildRestrictedInjector(Module module)
  64. {
  65. return Guice.createInjector(
  66. Stage.PRODUCTION,
  67. ImmutableList.of(module, (binder) -> {
  68. binder.disableCircularProxies();
  69. }));
  70. }
  71. }