1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2020 Jakub Kądziołka <kuba@kadziolka.net>
5 ;;; This file is part of GNU Guix.
7 ;;; GNU Guix is free software; you can redistribute it and/or modify it
8 ;;; under the terms of the GNU General Public License as published by
9 ;;; the Free Software Foundation; either version 3 of the License, or (at
10 ;;; your option) any later version.
12 ;;; GNU Guix is distributed in the hope that it will be useful, but
13 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;;; GNU General Public License for more details.
17 ;;; You should have received a copy of the GNU General Public License
18 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
20 (define-module (guix swh)
21 #:use-module (guix base16)
22 #:use-module (guix build utils)
23 #:use-module ((guix build syscalls) #:select (mkdtemp!))
24 #:use-module (web uri)
25 #:use-module (guix json)
26 #:use-module (web client)
27 #:use-module (web response)
29 #:use-module (srfi srfi-1)
30 #:use-module (srfi srfi-9)
31 #:use-module (srfi srfi-11)
32 #:use-module (srfi srfi-19)
33 #:use-module (ice-9 match)
34 #:use-module (ice-9 regex)
35 #:use-module (ice-9 popen)
36 #:use-module ((ice-9 ftw) #:select (scandir))
37 #:export (%swh-base-url
40 request-rate-limit-reached?
72 lookup-origin-revision
83 directory-entry-checksums
84 directory-entry-length
85 directory-entry-permissions
87 directory-entry-target
91 save-reply-origin-type
92 save-reply-request-date
93 save-reply-request-status
94 save-reply-task-status
100 vault-reply-fetch-url
101 vault-reply-object-id
102 vault-reply-object-type
103 vault-reply-progress-message
115 ;;; This module provides bindings to the HTTP interface of Software Heritage.
116 ;;; It allows you to browse the archive, look up revisions (such as SHA1
117 ;;; commit IDs), "origins" (code hosting URLs), content (files), etc. See
118 ;;; <https://archive.softwareheritage.org/api/> for more information.
120 ;;; The high-level 'swh-download' procedure allows you to download a Git
121 ;;; revision from Software Heritage, provided it is available.
125 (define %swh-base-url
126 ;; Presumably we won't need to change it.
127 (make-parameter "https://archive.softwareheritage.org"))
129 (define (swh-url path . rest)
130 ;; URLs returned by the API may be relative or absolute. This has changed
131 ;; without notice before. Handle both cases by detecting whether the path
132 ;; starts with a domain.
134 (if (string-prefix? "/" path)
135 (string-append (%swh-base-url) path)
139 (string-append root (string-join rest "/" 'prefix)))
141 ;; Ensure there's a trailing slash or we get a redirect.
142 (if (string-suffix? "/" url)
144 (string-append url "/")))
147 ;; Match strings like "2014-11-17T22:09:38+01:00" or
148 ;; "2018-09-30T23:20:07.815449+00:00"".
149 (make-regexp "^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})((\\.[0-9]+)?)([+-][0-9]{2}):([0-9]{2})$"))
151 (define (string->date* str)
152 "Return a SRFI-19 date parsed from STR, a date string as returned by
154 ;; We can't use 'string->date' because of the timezone format: SWH returns
155 ;; "+01:00" when the '~z' template expects "+0100". So we roll our own!
156 (or (and=> (regexp-exec %date-regexp str)
159 (string->number (match:substring match n)))
161 (make-date (let ((ns (match:substring match 8)))
163 (string->number (string-drop ns 1))
165 (ref 6) (ref 5) (ref 4)
166 (ref 3) (ref 2) (ref 1)
167 (+ (* 3600 (ref 9)) ;time zone
174 ;; Converts "string or #nil" coming from JSON to "string or #f".
176 ((? string? str) str)
179 (define %allow-request?
180 ;; Takes a URL and method (e.g., the 'http-get' procedure) and returns true
181 ;; to keep going. This can be used to disallow a requests when
182 ;; 'request-rate-limit-reached?' returns true, for instance.
183 (make-parameter (const #t)))
185 ;; The time when the rate limit for "/origin/save" POST requests and that of
186 ;; other requests will be reset.
187 ;; See <https://archive.softwareheritage.org/api/#rate-limiting>.
188 (define %save-rate-limit-reset-time 0)
189 (define %general-rate-limit-reset-time 0)
191 (define (request-rate-limit-reached? url method)
192 "Return true if the rate limit has been reached for URI."
197 (if (and (eq? method http-post)
198 (string-prefix? "/api/1/origin/save/" (uri-path uri)))
199 %save-rate-limit-reset-time
200 %general-rate-limit-reset-time))
202 (< (car (gettimeofday)) reset-time))
204 (define (update-rate-limit-reset-time! url method response)
205 "Update the rate limit reset time for URL and METHOD based on the headers in
207 (let ((uri (string->uri url)))
208 (match (assq-ref (response-headers response) 'x-ratelimit-reset)
209 ((= string->number (? number? reset))
210 (if (and (eq? method http-post)
211 (string-prefix? "/api/1/origin/save/" (uri-path uri)))
212 (set! %save-rate-limit-reset-time reset)
213 (set! %general-rate-limit-reset-time reset)))
217 (define* (call url decode #:optional (method http-get)
218 #:key (false-if-404? #t))
219 "Invoke the endpoint at URL using METHOD. Decode the resulting JSON body
220 using DECODE, a one-argument procedure that takes an input port. When
221 FALSE-IF-404? is true, return #f upon 404 responses."
222 (and ((%allow-request?) url method)
223 (let*-values (((response port)
224 (method url #:streaming? #t)))
225 ;; See <https://archive.softwareheritage.org/api/#rate-limiting>.
226 (match (assq-ref (response-headers response) 'x-ratelimit-remaining)
228 ((? (compose zero? string->number))
229 (update-rate-limit-reset-time! url method response)
230 (throw 'swh-error url method response))
233 (cond ((= 200 (response-code response))
234 (let ((result (decode port)))
238 (= 404 (response-code response)))
243 (throw 'swh-error url method response))))))
245 (define-syntax define-query
247 "Define a procedure that performs a Software Heritage query."
248 ((_ (name args ...) docstring (path components ...)
250 (define (name args ...)
252 (call (swh-url components ...) json->value)))))
254 ;; <https://archive.softwareheritage.org/api/1/origin/https://github.com/guix-mirror/guix/get>
255 (define-json-mapping <origin> make-origin origin?
257 (visits-url origin-visits-url "origin_visits_url")
261 ;; <https://archive.softwareheritage.org/api/1/origin/52181937/visits/>
262 (define-json-mapping <visit> make-visit visit?
264 (date visit-date "date" string->date*)
265 (origin visit-origin)
266 (url visit-url "origin_visit_url")
267 (snapshot-url visit-snapshot-url "snapshot_url" string*) ;string | #f
268 (status visit-status "status" string->symbol) ;'full | 'partial | 'ongoing
269 (number visit-number "visit"))
271 ;; <https://archive.softwareheritage.org/api/1/snapshot/4334c3ed4bb208604ed780d8687fe523837f1bd1/>
272 (define-json-mapping <snapshot> make-snapshot snapshot?
274 (branches snapshot-branches "branches" json->branches))
276 ;; This is used for the "branches" field of snapshots.
277 (define-record-type <branch>
278 (make-branch name target-type target-url)
281 (target-type branch-target-type) ;release | revision
282 (target-url branch-target-url))
284 (define (json->branches branches)
289 (assoc-ref value "target_type"))
290 (assoc-ref value "target_url"))))
293 ;; <https://archive.softwareheritage.org/api/1/release/1f44934fb6e2cefccbecd4fa347025349fa9ff76/>
294 (define-json-mapping <release> make-release release?
298 (message release-message)
299 (target-type release-target-type "target_type" string->symbol)
300 (target-url release-target-url "target_url"))
302 ;; <https://archive.softwareheritage.org/api/1/revision/359fdda40f754bbf1b5dc261e7427b75463b59be/>
303 (define-json-mapping <revision> make-revision revision?
306 (date revision-date "date" string->date*)
307 (directory revision-directory)
308 (directory-url revision-directory-url "directory_url"))
310 ;; <https://archive.softwareheritage.org/api/1/content/>
311 (define-json-mapping <content> make-content content?
313 (checksums content-checksums "checksums" json->checksums)
314 (data-url content-data-url "data_url")
315 (file-type-url content-file-type-url "filetype_url")
316 (language-url content-language-url "language_url")
317 (length content-length)
318 (license-url content-license-url "license_url"))
320 (define (json->checksums checksums)
323 (cons key (base16-string->bytevector value))))
326 ;; <https://archive.softwareheritage.org/api/1/directory/27c69c5d298a43096a53affbf881e7b13f17bdcd/>
327 (define-json-mapping <directory-entry> make-directory-entry directory-entry?
328 json->directory-entry
329 (name directory-entry-name)
330 (type directory-entry-type "type"
333 (str (string->symbol str))))
334 (checksums directory-entry-checksums "checksums"
337 (lst (json->checksums lst))))
338 (id directory-entry-id "dir_id")
339 (length directory-entry-length)
340 (permissions directory-entry-permissions "perms")
341 (target-url directory-entry-target-url "target_url"))
343 ;; <https://archive.softwareheritage.org/api/1/origin/save/>
344 (define-json-mapping <save-reply> make-save-reply save-reply?
346 (origin-url save-reply-origin-url "origin_url")
347 (origin-type save-reply-origin-type "origin_type")
348 (request-date save-reply-request-date "save_request_date"
350 (request-status save-reply-request-status "save_request_status"
352 (task-status save-reply-task-status "save_task_status"
354 ("not created" 'not-created)
355 ((? string? str) (string->symbol str)))))
357 ;; <https://docs.softwareheritage.org/devel/swh-vault/api.html#vault-api-ref>
358 (define-json-mapping <vault-reply> make-vault-reply vault-reply?
361 (fetch-url vault-reply-fetch-url "fetch_url")
362 (object-id vault-reply-object-id "obj_id")
363 (object-type vault-reply-object-type "obj_type" string->symbol)
364 (progress-message vault-reply-progress-message "progress_message")
365 (status vault-reply-status "status" string->symbol))
372 (define-query (lookup-origin url)
373 "Return an origin for URL."
374 (path "/api/1/origin" url "get")
377 (define-query (lookup-content hash type)
378 "Return a content for HASH, of the given TYPE--e.g., \"sha256\"."
379 (path "/api/1/content"
380 (string-append type ":"
381 (bytevector->base16-string hash)))
384 (define-query (lookup-revision id)
385 "Return the revision with the given ID, typically a Git commit SHA1."
386 (path "/api/1/revision" id)
389 (define-query (lookup-directory id)
390 "Return the directory with the given ID."
391 (path "/api/1/directory" id)
392 json->directory-entries)
394 (define (json->directory-entries port)
395 (map json->directory-entry
396 (vector->list (json->scm port))))
398 (define (origin-visits origin)
399 "Return the list of visits of ORIGIN, a record as returned by
401 (call (swh-url (origin-visits-url origin))
403 (map json->visit (vector->list (json->scm port))))))
405 (define (visit-snapshot visit)
406 "Return the snapshot corresponding to VISIT or #f if no snapshot is
408 (and (visit-snapshot-url visit)
409 (call (swh-url (visit-snapshot-url visit))
412 (define (branch-target branch)
413 "Return the target of BRANCH, either a <revision> or a <release>."
414 (match (branch-target-type branch)
416 (call (swh-url (branch-target-url branch))
419 (call (swh-url (branch-target-url branch))
422 (define (lookup-origin-revision url tag)
423 "Return a <revision> corresponding to the given TAG for the repository
424 coming from URL. Example:
426 (lookup-origin-revision \"https://github.com/guix-mirror/guix/\" \"v0.8\")
427 => #<<revision> id: \"44941…\" …>
429 The information is based on the latest visit of URL available. Return #f if
430 URL could not be found."
431 (match (lookup-origin url)
434 (match (filter visit-snapshot-url (origin-visits origin))
436 (let ((snapshot (visit-snapshot visit)))
437 (match (and=> (find (lambda (branch)
438 (string=? (string-append "refs/tags/" tag)
439 (branch-name branch)))
440 (snapshot-branches snapshot))
442 ((? release? release)
443 (release-target release))
444 ((? revision? revision)
451 (define (release-target release)
452 "Return the revision that is the target of RELEASE."
453 (match (release-target-type release)
455 (call (swh-url (release-target-url release))
458 (define (directory-entry-target entry)
459 "If ENTRY, a directory entry, has type 'directory, return its list of
460 directory entries; if it has type 'file, return its <content> object."
461 (call (swh-url (directory-entry-target-url entry))
462 (match (directory-entry-type entry)
463 ('file json->content)
464 ('directory json->directory-entries))))
466 (define* (save-origin url #:optional (type "git"))
467 "Request URL to be saved."
468 (call (swh-url "/api/1/origin/save" type "url" url) json->save-reply
471 (define-query (save-origin-status url type)
472 "Return the status of a /save request for URL and TYPE (e.g., \"git\")."
473 (path "/api/1/origin/save" type "url" url)
476 (define-query (query-vault id kind)
477 "Ask the availability of object ID and KIND to the vault, where KIND is
478 'directory or 'revision. Return #f if it could not be found, or a
479 <vault-reply> on success."
480 ;; <https://docs.softwareheritage.org/devel/swh-vault/api.html#vault-api-ref>
481 ;; There's a single format supported for directories and revisions and for
482 ;; now, the "/format" bit of the URL *must* be omitted.
483 (path "/api/1/vault" (symbol->string kind) id)
486 (define (request-cooking id kind)
487 "Request the cooking of object ID and KIND (one of 'directory or 'revision)
488 to the vault. Return a <vault-reply>."
489 (call (swh-url "/api/1/vault" (symbol->string kind) id)
493 (define* (vault-fetch id kind
494 #:key (log-port (current-error-port)))
495 "Return an input port from which a bundle of the object with the given ID
496 and KIND (one of 'directory or 'revision) can be retrieved, or #f if the
497 object could not be found.
499 For a directory, the returned stream is a gzip-compressed tarball. For a
500 revision, it is a gzip-compressed stream for 'git fast-import'."
501 (let loop ((reply (query-vault id kind)))
504 (and=> (request-cooking id kind) loop))
506 (match (vault-reply-status reply)
509 (let-values (((response port)
510 (http-get (swh-url (vault-reply-fetch-url reply))
512 (if (= (response-code response) 200)
514 (begin ;shouldn't happen
518 ;; Upon failure, we're supposed to try again.
519 (format log-port "SWH vault: failure: ~a~%"
520 (vault-reply-progress-message reply))
521 (format log-port "SWH vault: retrying...~%")
522 (loop (request-cooking id kind)))
523 ((and (or 'new 'pending) status)
524 ;; Wait until the bundle shows up.
525 (let ((message (vault-reply-progress-message reply)))
526 (when (eq? 'new status)
527 (format log-port "SWH vault: \
528 requested bundle cooking, waiting for completion...~%"))
529 (when (string? message)
530 (format log-port "SWH vault: ~a~%" message))
532 ;; Wait long enough so we don't exhaust our maximum number of
533 ;; requests per hour too fast (as of this writing, the limit is 60
534 ;; requests per hour per IP address.)
535 (sleep (if (eq? status 'new) 60 30))
537 (loop (query-vault id kind)))))))))
541 ;;; High-level interface.
544 (define (commit-id? reference)
545 "Return true if REFERENCE is likely a commit ID, false otherwise---e.g., if
546 it is a tag name. This is based on a simple heuristic so use with care!"
547 (and (= (string-length reference) 40)
548 (string-every char-set:hex-digit reference)))
550 (define (call-with-temporary-directory proc) ;FIXME: factorize
551 "Call PROC with a name of a temporary directory; close the directory and
552 delete it when leaving the dynamic extent of this call."
553 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
554 (template (string-append directory "/guix-directory.XXXXXX"))
555 (tmp-dir (mkdtemp! template)))
561 (false-if-exception (delete-file-recursively tmp-dir))))))
563 (define* (swh-download url reference output
564 #:key (log-port (current-error-port)))
565 "Download from Software Heritage a checkout of the Git tag or commit
566 REFERENCE originating from URL, and unpack it in OUTPUT. Return #t on success
569 This procedure uses the \"vault\", which contains \"cooked\" directories in
570 the form of tarballs. If the requested directory is not cooked yet, it will
571 wait until it becomes available, which could take several minutes."
572 (match (if (commit-id? reference)
573 (lookup-revision reference)
574 (lookup-origin-revision url reference))
575 ((? revision? revision)
576 (format log-port "SWH: found revision ~a with directory at '~a'~%"
577 (revision-id revision)
578 (swh-url (revision-directory-url revision)))
579 (call-with-temporary-directory
581 (match (vault-fetch (revision-directory revision) 'directory
585 "SWH: directory ~a could not be fetched from the vault~%"
586 (revision-directory revision))
589 (let ((tar (open-pipe* OPEN_WRITE "tar" "-C" directory "-xzvf" "-")))
590 (dump-port input tar)
592 (let ((status (close-pipe tar)))
593 (unless (zero? status)
594 (error "tar extraction failure" status)))
596 (match (scandir directory)
597 (("." ".." sub-directory)
598 (copy-recursively (string-append directory "/" sub-directory)
600 #:log (%make-void-port "w"))