001package org.hl7.fhir.utilities.npm;
002
003import java.io.IOException;
004import java.io.InputStream;
005import java.util.ArrayList;
006import java.util.List;
007import java.util.function.Function;
008
009import javax.annotation.Nonnull;
010import javax.annotation.Nullable;
011
012import lombok.extern.slf4j.Slf4j;
013import org.apache.commons.lang3.Validate;
014import org.hl7.fhir.exceptions.FHIRException;
015import org.hl7.fhir.utilities.Utilities;
016import org.hl7.fhir.utilities.VersionUtilities;
017
018@Slf4j
019public abstract class BasePackageCacheManager implements IPackageCacheManager {
020
021  protected final List<PackageServer> myPackageServers;
022  private Function<PackageServer, PackageClient> myClientFactory = server -> new PackageClient(server);
023
024  /**
025   * Constructor
026   */
027  public BasePackageCacheManager() {
028    super();
029    myPackageServers = new ArrayList<>();
030  }
031
032  protected BasePackageCacheManager(@Nonnull List<PackageServer> thePackageServers) {
033    myPackageServers = thePackageServers;
034  }
035  /**
036   * Provide a new client factory implementation
037   */
038  public void setClientFactory(Function<PackageServer, PackageClient> theClientFactory) {
039    Validate.notNull(theClientFactory, "theClientFactory must not be null");
040    myClientFactory = theClientFactory;
041  }
042
043  public List<PackageServer> getPackageServers() {
044    return myPackageServers;
045  }
046
047  /**
048   * Add a package server that can be used to fetch remote packages
049   */
050  public void addPackageServer(@Nonnull PackageServer thePackageServer) {
051    Validate.notNull(thePackageServer, "thePackageServer must not be null or empty");
052    if (!myPackageServers.contains(thePackageServer)) {
053      myPackageServers.add(thePackageServer);
054    }
055  }
056
057
058  /**
059   * Load the latest version of the identified package from the cache - it it exists
060   */
061  public NpmPackage loadPackageFromCacheOnly(String id) throws IOException {
062    return loadPackageFromCacheOnly(id, null);
063  }
064
065  /**
066   * Try to load a package from all registered package servers, and return <code>null</code>
067   * if it can not be found at any of them.
068   */
069  @Nullable
070  protected InputStreamWithSrc loadFromPackageServer(String id, String version) {
071
072    for (PackageServer nextPackageServer : getPackageServers()) {
073      if (okToUsePackageServer(nextPackageServer.getUrl(), id)) {
074        PackageClient packageClient = myClientFactory.apply(nextPackageServer);
075        try {
076          if (Utilities.noString(version)) {
077            version = packageClient.getLatestVersion(id, false);
078          }
079          if (VersionUtilities.versionHasWildcards(version)) {
080            version = packageClient.getLatestVersion(id, version);
081            if (version == null) {
082              return null;
083            }
084          }
085
086          InputStream stream = packageClient.fetch(id, version);
087          String url = packageClient.url(id, version);
088          return new InputStreamWithSrc(stream, url, version);
089        } catch (IOException e) {
090          log.debug("Failed to resolve package {}#{} from server: {} ({})", id, version, nextPackageServer, e.getMessage());
091        }
092      }
093    }
094
095    return null;
096  }
097
098  // hack - we have a hacked 1.4.0 out there. Only packages2.fhir.org has it.
099  // this is not a long term thing, but it's not clear how to release patches for 
100  // 1.4.0
101  private boolean okToUsePackageServer(String server, String id) {
102    if (PackageServer.PRIMARY_SERVER.equals(server) && "hl7.fhir.r2b.core".equals(id)) {
103      return false;
104    }
105    return true;
106  }
107
108  public abstract NpmPackage loadPackageFromCacheOnly(String id, @Nullable String version) throws IOException;
109
110  @Override
111  public String getPackageUrl(String packageId) throws IOException {
112    packageId = stripAlias(packageId);
113    String result = null;
114    NpmPackage npm = loadPackageFromCacheOnly(packageId);
115    if (npm != null) {
116      return npm.canonical();
117    }
118
119    for (PackageServer nextPackageServer : getPackageServers()) {
120      result = getPackageUrl(packageId, nextPackageServer);
121      if (result != null) {
122        return result;
123      }
124    }
125
126    return result;
127  }
128
129
130  private String getPackageUrl(String packageId, PackageServer server) throws IOException {
131    PackageClient pc = myClientFactory.apply(server);
132    List<PackageInfo> res = pc.search(packageId, null, null, false, null);
133    if (res.size() == 0) {
134      return null;
135    } else {
136      return res.get(0).getUrl();
137    }
138  }
139
140
141  @Override
142  public String getPackageId(String canonicalUrl) throws IOException {
143    String result = null;
144
145    for (PackageServer nextPackageServer : getPackageServers()) {
146      result = getPackageId(canonicalUrl, nextPackageServer);
147      if (result != null) {
148        break;
149      }
150    }
151
152    return result;
153  }
154
155  private String getPackageId(String canonical, PackageServer server) throws IOException {
156    if (canonical == null) {
157      return null;
158    }
159    PackageClient pc = myClientFactory.apply(server);
160    List<PackageInfo> res = pc.search(null, canonical, null, false, null);
161    if (res.size() == 0) {
162      return null;
163    } else {
164      // this is driven by HL7 Australia (http://hl7.org.au/fhir/ is the canonical url for the base package, and the root for all the others)
165      for (PackageInfo pi : res) {
166        if (canonical.equals(pi.getCanonical())) {
167          return pi.getId();
168        }
169      }
170      return res.get(0).getId();
171    }
172  }
173
174  public static class InputStreamWithSrc {
175
176    public InputStream stream;
177    public String url;
178    public String version;
179
180    public InputStreamWithSrc(InputStream stream, String url, String version) {
181      this.stream = stream;
182      this.url = url;
183      this.version = version;
184    }
185  }
186
187  @Override
188  public NpmPackage loadPackage(String idAndVer) throws FHIRException, IOException {
189    idAndVer = stripAlias(idAndVer);
190    return loadPackage(idAndVer, null);
191  }
192
193
194  /**
195   * The NPM Alias format is:
196   *   npm install <alias>@npm:<name>:
197   *   
198   * (see https://docs.npmjs.com/cli/v8/commands/npm-install)
199   * 
200   * We're using that format to allow us to use more than one version of the same package in packages.json,
201   * but what the prefix actually is is irrelevant here - we just load the actual package the user 
202   * is interested in
203   * 
204   * Corollary: you will get a different package name than you asked for when using aliases
205   * 
206   * @param id
207   * @return
208   */
209  protected String stripAlias(String id) {
210    if (id != null && id.contains("@npm:")) {
211      return id.substring(id.indexOf("@npm:")+5);
212    } else {
213      return id;
214    }
215  }
216}