001package org.hl7.fhir.utilities.npm;
002
003import lombok.Getter;
004import org.hl7.fhir.exceptions.FHIRException;
005import org.hl7.fhir.utilities.FileUtilities;
006import org.hl7.fhir.utilities.Utilities;
007import org.hl7.fhir.utilities.http.HTTPResult;
008import org.hl7.fhir.utilities.http.ManagedWebAccess;
009import org.hl7.fhir.utilities.json.model.JsonArray;
010import org.hl7.fhir.utilities.json.model.JsonElement;
011import org.hl7.fhir.utilities.json.model.JsonObject;
012import org.hl7.fhir.utilities.json.parser.JsonParser;
013
014import java.io.ByteArrayInputStream;
015import java.io.IOException;
016import java.io.InputStream;
017import java.text.ParseException;
018import java.text.SimpleDateFormat;
019import java.util.*;
020
021public class CIBuildClient {
022
023  private static final String DEFAULT_ROOT_URL = "https://build.fhir.org";
024  private static final long DEFAULT_CI_QUERY_INTERVAL = 1000 * 60 * 60;
025  private final long ciQueryInterval;
026
027  @Getter
028  private long ciLastQueriedTimeStamp = 0;
029
030  @Getter
031  private JsonArray ciBuildInfo;
032
033  @Getter
034  private final String rootUrl;
035
036  /**
037   * key = packageId
038   * value = url of built package on https://build.fhir.org/ig/
039   **/
040  private final Map<String, String> ciPackageUrls = new HashMap<>();
041
042  private final boolean silent;
043
044  public CIBuildClient() {
045   this(DEFAULT_ROOT_URL, DEFAULT_CI_QUERY_INTERVAL, false);
046  }
047
048  public CIBuildClient(String rootUrl, long ciQueryInterval, boolean silent) {
049    this.rootUrl = rootUrl;
050    this.ciQueryInterval = ciQueryInterval;
051    this.silent = silent;
052  }
053
054  String getPackageId(String canonical) {
055    if (canonical == null) {
056      return null;
057    }
058    checkCIServerQueried();
059    if (ciBuildInfo != null) {
060      for (JsonElement n : ciBuildInfo) {
061        JsonObject o = (JsonObject) n;
062        if (canonical.equals(o.asString("url"))) {
063          return o.asString("package-id");
064        }
065      }
066      for (JsonElement n : ciBuildInfo) {
067        JsonObject o = (JsonObject) n;
068        if (o.asString("url").startsWith(canonical + "/ImplementationGuide/")) {
069          return o.asString("package-id");
070        }
071      }
072    }
073    return null;
074  }
075
076  String getPackageUrl(String packageId) {
077    checkCIServerQueried();
078    for (JsonObject o : ciBuildInfo.asJsonObjects()) {
079      if (packageId.equals(o.asString("package-id"))) {
080        return o.asString("url");
081      }
082    }
083    return null;
084  }
085
086  public boolean isCurrent(String id, NpmPackage npmPackage) throws IOException {
087    checkCIServerQueried();
088    String packageManifestUrl = ciPackageUrls.get(id);
089    JsonObject packageManifestJson = JsonParser.parseObjectFromUrl(Utilities.pathURL(packageManifestUrl, "package.manifest.json"));
090    String currentDate = packageManifestJson.asString("date");
091    String packageDate = npmPackage.date();
092    return currentDate.equals(packageDate); // nup, we need a new copy
093  }
094
095  BasePackageCacheManager.InputStreamWithSrc loadFromCIBuild(String id, String branch) {
096    checkCIServerQueried();
097
098    if (ciPackageUrls.containsKey(id)) {
099      String packageBaseUrl = ciPackageUrls.get(id);
100      if (branch == null) {
101        InputStream stream;
102        try {
103          stream = fetchFromUrlSpecific(Utilities.pathURL(packageBaseUrl, "package.tgz"));
104        } catch (Exception e) {
105          stream = fetchFromUrlSpecific(Utilities.pathURL(packageBaseUrl, "branches", "main", "package.tgz"));
106        }
107        return new BasePackageCacheManager.InputStreamWithSrc(stream, Utilities.pathURL(packageBaseUrl, "package.tgz"), "current");
108      } else {
109        InputStream stream = fetchFromUrlSpecific(Utilities.pathURL(packageBaseUrl, "branches", branch, "package.tgz"));
110        return new BasePackageCacheManager.InputStreamWithSrc(stream, Utilities.pathURL(packageBaseUrl, "branches", branch, "package.tgz"), "current$" + branch);
111      }
112    } else if (id.startsWith("hl7.fhir.r6")) {
113      InputStream stream = fetchFromUrlSpecific(Utilities.pathURL(rootUrl, id + ".tgz"));
114      return new BasePackageCacheManager.InputStreamWithSrc(stream, Utilities.pathURL(rootUrl, id + ".tgz"), "current");
115    } else if (id.startsWith("hl7.fhir.uv.extensions.")) {
116      InputStream stream = fetchFromUrlSpecific(Utilities.pathURL(rootUrl + "/ig/HL7/fhir-extensions/", id + ".tgz"));
117      return new BasePackageCacheManager.InputStreamWithSrc(stream, Utilities.pathURL(rootUrl + "/ig/HL7/fhir-extensions/", id + ".tgz"), "current");
118    } else {
119      throw new FHIRException("The package '" + id + "' has no entry on the current build server (" + ciPackageUrls + ")");
120    }
121  }
122
123  private InputStream fetchFromUrlSpecific(String source) throws FHIRException {
124    try {
125      HTTPResult res = ManagedWebAccess.get(Arrays.asList("web"), source);
126      res.checkThrowException();
127      return new ByteArrayInputStream(res.getContent());
128    } catch (Exception e) {
129        throw new FHIRException("Unable to fetch: " + e.getMessage(), e);
130    }
131  }
132
133  private void checkCIServerQueried() {
134    if (System.currentTimeMillis() - ciLastQueriedTimeStamp > ciQueryInterval) {
135      try {
136        updateFromCIServer();
137      } catch (Exception e) {
138        try {
139          // we always pause a second and try again - the most common reason to be here is that the file was being changed on the server
140          Thread.sleep(1000);
141          updateFromCIServer();
142        } catch (Exception e2) {
143          if (!silent) {
144            System.out.println("Error connecting to build server - running without build (" + e2.getMessage() + ")");
145          }
146        }
147      }
148    }
149  }
150
151  private void updateFromCIServer() throws IOException {
152    HTTPResult res = ManagedWebAccess.get(Arrays.asList("web"), rootUrl + "/ig/qas.json?nocache=" + System.currentTimeMillis());
153    res.checkThrowException();
154
155    ciBuildInfo = (JsonArray) JsonParser.parse(FileUtilities.bytesToString(res.getContent()));
156
157    List<BuildRecord> builds = new ArrayList<>();
158
159    for (JsonElement n : ciBuildInfo) {
160      JsonObject j = (JsonObject) n;
161      if (j.has("url") && j.has("package-id") && j.asString("package-id").contains(".")) {
162        String packageUrl = j.asString("url");
163        if (packageUrl.contains("/ImplementationGuide/"))
164          packageUrl = packageUrl.substring(0, packageUrl.indexOf("/ImplementationGuide/"));
165        builds.add(new BuildRecord(packageUrl, j.asString("package-id"), getRepo(j.asString("repo")), readDate(j.asString("date"))));
166      }
167    }
168    Collections.sort(builds, new BuildRecordSorter());
169    for (BuildRecord build : builds) {
170      if (!ciPackageUrls.containsKey(build.getPackageId())) {
171        ciPackageUrls.put(build.getPackageId(), rootUrl + "/ig/" + build.getRepo());
172      }
173    }
174    ciLastQueriedTimeStamp = System.currentTimeMillis();
175  }
176
177  private String getRepo(String path) {
178    String[] p = path.split("/");
179    return p[0] + "/" + p[1];
180  }
181
182  private Date readDate(String s) {
183    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM, yyyy HH:mm:ss Z", new Locale("en", "US"));
184    try {
185      return sdf.parse(s);
186    } catch (ParseException e) {
187      e.printStackTrace();
188      return new Date();
189    }
190  }
191
192  public static class BuildRecord {
193
194    private final String url;
195    private final String packageId;
196    private final String repo;
197    private final Date date;
198
199    public BuildRecord(String url, String packageId, String repo, Date date) {
200      super();
201      this.url = url;
202      this.packageId = packageId;
203      this.repo = repo;
204      this.date = date;
205    }
206
207    public String getUrl() {
208      return url;
209    }
210
211    public String getPackageId() {
212      return packageId;
213    }
214
215    public String getRepo() {
216      return repo;
217    }
218
219    public Date getDate() {
220      return date;
221    }
222
223  }
224
225  public static class BuildRecordSorter implements Comparator<BuildRecord> {
226
227    @Override
228    public int compare(BuildRecord arg0, BuildRecord arg1) {
229      return arg1.date.compareTo(arg0.date);
230    }
231  }
232}