Add (guix json).
[jackhill/guix/guix.git] / guix / swh.scm
CommitLineData
de2bfe90 1;;; GNU Guix --- Functional package management for GNU
96f1cbef 2;;; Copyright © 2018, 2019 Ludovic Courtès <ludo@gnu.org>
de2bfe90
LC
3;;;
4;;; This file is part of GNU Guix.
5;;;
6;;; GNU Guix is free software; you can redistribute it and/or modify it
7;;; under the terms of the GNU General Public License as published by
8;;; the Free Software Foundation; either version 3 of the License, or (at
9;;; your option) any later version.
10;;;
11;;; GNU Guix is distributed in the hope that it will be useful, but
12;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
18
19(define-module (guix swh)
20 #:use-module (guix base16)
21 #:use-module (guix build utils)
22 #:use-module ((guix build syscalls) #:select (mkdtemp!))
ba1c1853 23 #:use-module (web uri)
76073d29 24 #:use-module (guix json)
de2bfe90
LC
25 #:use-module (web client)
26 #:use-module (web response)
27 #:use-module (json)
28 #:use-module (srfi srfi-1)
29 #:use-module (srfi srfi-9)
30 #:use-module (srfi srfi-11)
31 #:use-module (srfi srfi-19)
32 #:use-module (ice-9 match)
33 #:use-module (ice-9 regex)
34 #:use-module (ice-9 popen)
35 #:use-module ((ice-9 ftw) #:select (scandir))
96f1cbef 36 #:export (%swh-base-url
ba1c1853
LC
37 %allow-request?
38
39 request-rate-limit-reached?
96f1cbef
LC
40
41 origin?
de2bfe90
LC
42 origin-id
43 origin-type
44 origin-url
45 origin-visits
46 lookup-origin
47
48 visit?
49 visit-date
50 visit-origin
51 visit-url
52 visit-snapshot-url
53 visit-status
54 visit-number
55 visit-snapshot
56
57 branch?
58 branch-name
59 branch-target
60
61 release?
62 release-id
63 release-name
64 release-message
65 release-target
66
67 revision?
68 revision-id
69 revision-date
70 revision-directory
71 lookup-revision
72 lookup-origin-revision
73
74 content?
75 content-checksums
76 content-data-url
77 content-length
78 lookup-content
79
80 directory-entry?
81 directory-entry-name
82 directory-entry-type
83 directory-entry-checksums
84 directory-entry-length
85 directory-entry-permissions
86 lookup-directory
87 directory-entry-target
88
ee6b3bb6
LC
89 save-reply?
90 save-reply-origin-url
91 save-reply-origin-type
92 save-reply-request-date
93 save-reply-request-status
94 save-reply-task-status
95 save-origin
96 save-origin-status
97
de2bfe90
LC
98 vault-reply?
99 vault-reply-id
100 vault-reply-fetch-url
101 vault-reply-object-id
102 vault-reply-object-type
103 vault-reply-progress-message
104 vault-reply-status
105 query-vault
106 request-cooking
107 vault-fetch
108
d370cc73
LC
109 commit-id?
110
de2bfe90
LC
111 swh-download))
112
113;;; Commentary:
114;;;
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.
119;;;
120;;; The high-level 'swh-download' procedure allows you to download a Git
121;;; revision from Software Heritage, provided it is available.
122;;;
123;;; Code:
124
125(define %swh-base-url
126 ;; Presumably we won't need to change it.
96f1cbef 127 (make-parameter "https://archive.softwareheritage.org"))
de2bfe90
LC
128
129(define (swh-url path . rest)
130 (define url
96f1cbef 131 (string-append (%swh-base-url) path
de2bfe90
LC
132 (string-join rest "/" 'prefix)))
133
134 ;; Ensure there's a trailing slash or we get a redirect.
135 (if (string-suffix? "/" url)
136 url
137 (string-append url "/")))
138
de2bfe90
LC
139(define %date-regexp
140 ;; Match strings like "2014-11-17T22:09:38+01:00" or
141 ;; "2018-09-30T23:20:07.815449+00:00"".
142 (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})$"))
143
144(define (string->date* str)
145 "Return a SRFI-19 date parsed from STR, a date string as returned by
146Software Heritage."
147 ;; We can't use 'string->date' because of the timezone format: SWH returns
148 ;; "+01:00" when the '~z' template expects "+0100". So we roll our own!
149 (or (and=> (regexp-exec %date-regexp str)
150 (lambda (match)
151 (define (ref n)
152 (string->number (match:substring match n)))
153
154 (make-date (let ((ns (match:substring match 8)))
155 (if ns
156 (string->number (string-drop ns 1))
157 0))
158 (ref 6) (ref 5) (ref 4)
159 (ref 3) (ref 2) (ref 1)
160 (+ (* 3600 (ref 9)) ;time zone
161 (if (< (ref 9) 0)
162 (- (ref 10))
163 (ref 10))))))
164 str)) ;oops!
165
8146c486
LC
166(define string*
167 ;; Converts "string or #nil" coming from JSON to "string or #f".
168 (match-lambda
169 ((? string? str) str)
170 ((? null?) #f)))
171
ba1c1853
LC
172(define %allow-request?
173 ;; Takes a URL and method (e.g., the 'http-get' procedure) and returns true
174 ;; to keep going. This can be used to disallow a requests when
175 ;; 'request-rate-limit-reached?' returns true, for instance.
176 (make-parameter (const #t)))
177
178;; The time when the rate limit for "/origin/save" POST requests and that of
179;; other requests will be reset.
180;; See <https://archive.softwareheritage.org/api/#rate-limiting>.
181(define %save-rate-limit-reset-time 0)
182(define %general-rate-limit-reset-time 0)
183
184(define (request-rate-limit-reached? url method)
185 "Return true if the rate limit has been reached for URI."
186 (define uri
187 (string->uri url))
188
189 (define reset-time
190 (if (and (eq? method http-post)
191 (string-prefix? "/api/1/origin/save/" (uri-path uri)))
192 %save-rate-limit-reset-time
193 %general-rate-limit-reset-time))
194
195 (< (car (gettimeofday)) reset-time))
196
197(define (update-rate-limit-reset-time! url method response)
198 "Update the rate limit reset time for URL and METHOD based on the headers in
199RESPONSE."
200 (let ((uri (string->uri url)))
201 (match (assq-ref (response-headers response) 'x-ratelimit-reset)
202 ((= string->number (? number? reset))
203 (if (and (eq? method http-post)
204 (string-prefix? "/api/1/origin/save/" (uri-path uri)))
205 (set! %save-rate-limit-reset-time reset)
206 (set! %general-rate-limit-reset-time reset)))
207 (_
208 #f))))
209
de2bfe90
LC
210(define* (call url decode #:optional (method http-get)
211 #:key (false-if-404? #t))
212 "Invoke the endpoint at URL using METHOD. Decode the resulting JSON body
213using DECODE, a one-argument procedure that takes an input port. When
214FALSE-IF-404? is true, return #f upon 404 responses."
ba1c1853
LC
215 (and ((%allow-request?) url method)
216 (let*-values (((response port)
217 (method url #:streaming? #t)))
218 ;; See <https://archive.softwareheritage.org/api/#rate-limiting>.
219 (match (assq-ref (response-headers response) 'x-ratelimit-remaining)
220 (#f #t)
221 ((? (compose zero? string->number))
222 (update-rate-limit-reset-time! url method response)
223 (throw 'swh-error url method response))
224 (_ #t))
225
226 (cond ((= 200 (response-code response))
227 (let ((result (decode port)))
228 (close-port port)
229 result))
230 ((and false-if-404?
231 (= 404 (response-code response)))
232 (close-port port)
233 #f)
234 (else
235 (close-port port)
236 (throw 'swh-error url method response))))))
de2bfe90
LC
237
238(define-syntax define-query
239 (syntax-rules (path)
240 "Define a procedure that performs a Software Heritage query."
241 ((_ (name args ...) docstring (path components ...)
242 json->value)
243 (define (name args ...)
244 docstring
245 (call (swh-url components ...) json->value)))))
246
247;; <https://archive.softwareheritage.org/api/1/origin/git/url/https://github.com/guix-mirror/guix/>
248(define-json-mapping <origin> make-origin origin?
249 json->origin
250 (id origin-id)
251 (visits-url origin-visits-url "origin_visits_url")
252 (type origin-type)
253 (url origin-url))
254
255;; <https://archive.softwareheritage.org/api/1/origin/52181937/visits/>
256(define-json-mapping <visit> make-visit visit?
257 json->visit
258 (date visit-date "date" string->date*)
259 (origin visit-origin)
260 (url visit-url "origin_visit_url")
8146c486
LC
261 (snapshot-url visit-snapshot-url "snapshot_url" string*) ;string | #f
262 (status visit-status "status" string->symbol) ;'full | 'partial | 'ongoing
de2bfe90
LC
263 (number visit-number "visit"))
264
265;; <https://archive.softwareheritage.org/api/1/snapshot/4334c3ed4bb208604ed780d8687fe523837f1bd1/>
266(define-json-mapping <snapshot> make-snapshot snapshot?
267 json->snapshot
268 (branches snapshot-branches "branches" json->branches))
269
270;; This is used for the "branches" field of snapshots.
271(define-record-type <branch>
272 (make-branch name target-type target-url)
273 branch?
274 (name branch-name)
275 (target-type branch-target-type) ;release | revision
276 (target-url branch-target-url))
277
278(define (json->branches branches)
81c3dc32
LC
279 (map (match-lambda
280 ((key . value)
281 (make-branch key
282 (string->symbol
283 (assoc-ref value "target_type"))
284 (assoc-ref value "target_url"))))
285 branches))
de2bfe90
LC
286
287;; <https://archive.softwareheritage.org/api/1/release/1f44934fb6e2cefccbecd4fa347025349fa9ff76/>
288(define-json-mapping <release> make-release release?
289 json->release
290 (id release-id)
291 (name release-name)
292 (message release-message)
293 (target-type release-target-type "target_type" string->symbol)
294 (target-url release-target-url "target_url"))
295
296;; <https://archive.softwareheritage.org/api/1/revision/359fdda40f754bbf1b5dc261e7427b75463b59be/>
297(define-json-mapping <revision> make-revision revision?
298 json->revision
299 (id revision-id)
300 (date revision-date "date" string->date*)
301 (directory revision-directory)
302 (directory-url revision-directory-url "directory_url"))
303
304;; <https://archive.softwareheritage.org/api/1/content/>
305(define-json-mapping <content> make-content content?
306 json->content
307 (checksums content-checksums "checksums" json->checksums)
308 (data-url content-data-url "data_url")
309 (file-type-url content-file-type-url "filetype_url")
310 (language-url content-language-url "language_url")
311 (length content-length)
312 (license-url content-license-url "license_url"))
313
314(define (json->checksums checksums)
81c3dc32
LC
315 (map (match-lambda
316 ((key . value)
317 (cons key (base16-string->bytevector value))))
318 checksums))
de2bfe90
LC
319
320;; <https://archive.softwareheritage.org/api/1/directory/27c69c5d298a43096a53affbf881e7b13f17bdcd/>
321(define-json-mapping <directory-entry> make-directory-entry directory-entry?
322 json->directory-entry
323 (name directory-entry-name)
324 (type directory-entry-type "type"
325 (match-lambda
326 ("dir" 'directory)
327 (str (string->symbol str))))
328 (checksums directory-entry-checksums "checksums"
329 (match-lambda
330 (#f #f)
331 (lst (json->checksums lst))))
332 (id directory-entry-id "dir_id")
333 (length directory-entry-length)
334 (permissions directory-entry-permissions "perms")
335 (target-url directory-entry-target-url "target_url"))
336
337;; <https://archive.softwareheritage.org/api/1/origin/save/>
338(define-json-mapping <save-reply> make-save-reply save-reply?
339 json->save-reply
340 (origin-url save-reply-origin-url "origin_url")
341 (origin-type save-reply-origin-type "origin_type")
342 (request-date save-reply-request-date "save_request_date"
343 string->date*)
344 (request-status save-reply-request-status "save_request_status"
345 string->symbol)
346 (task-status save-reply-task-status "save_task_status"
347 (match-lambda
348 ("not created" 'not-created)
349 ((? string? str) (string->symbol str)))))
350
351;; <https://docs.softwareheritage.org/devel/swh-vault/api.html#vault-api-ref>
352(define-json-mapping <vault-reply> make-vault-reply vault-reply?
353 json->vault-reply
354 (id vault-reply-id)
355 (fetch-url vault-reply-fetch-url "fetch_url")
356 (object-id vault-reply-object-id "obj_id")
357 (object-type vault-reply-object-type "obj_type" string->symbol)
358 (progress-message vault-reply-progress-message "progress_message")
359 (status vault-reply-status "status" string->symbol))
360
361\f
362;;;
363;;; RPCs.
364;;;
365
366(define-query (lookup-origin url)
367 "Return an origin for URL."
368 (path "/api/1/origin/git/url" url)
369 json->origin)
370
371(define-query (lookup-content hash type)
372 "Return a content for HASH, of the given TYPE--e.g., \"sha256\"."
373 (path "/api/1/content"
374 (string-append type ":"
375 (bytevector->base16-string hash)))
376 json->content)
377
378(define-query (lookup-revision id)
379 "Return the revision with the given ID, typically a Git commit SHA1."
380 (path "/api/1/revision" id)
381 json->revision)
382
383(define-query (lookup-directory id)
384 "Return the directory with the given ID."
385 (path "/api/1/directory" id)
386 json->directory-entries)
387
388(define (json->directory-entries port)
81c3dc32
LC
389 (map json->directory-entry
390 (vector->list (json->scm port))))
de2bfe90
LC
391
392(define (origin-visits origin)
393 "Return the list of visits of ORIGIN, a record as returned by
394'lookup-origin'."
395 (call (swh-url (origin-visits-url origin))
396 (lambda (port)
81c3dc32 397 (map json->visit (vector->list (json->scm port))))))
de2bfe90
LC
398
399(define (visit-snapshot visit)
8146c486
LC
400 "Return the snapshot corresponding to VISIT or #f if no snapshot is
401available."
402 (and (visit-snapshot-url visit)
403 (call (swh-url (visit-snapshot-url visit))
404 json->snapshot)))
de2bfe90
LC
405
406(define (branch-target branch)
407 "Return the target of BRANCH, either a <revision> or a <release>."
408 (match (branch-target-type branch)
409 ('release
410 (call (swh-url (branch-target-url branch))
411 json->release))
412 ('revision
413 (call (swh-url (branch-target-url branch))
414 json->revision))))
415
416(define (lookup-origin-revision url tag)
417 "Return a <revision> corresponding to the given TAG for the repository
418coming from URL. Example:
419
8146c486 420 (lookup-origin-revision \"https://github.com/guix-mirror/guix/\" \"v0.8\")
de2bfe90
LC
421 => #<<revision> id: \"44941…\" …>
422
423The information is based on the latest visit of URL available. Return #f if
424URL could not be found."
425 (match (lookup-origin url)
426 (#f #f)
427 (origin
8146c486 428 (match (filter visit-snapshot-url (origin-visits origin))
de2bfe90
LC
429 ((visit . _)
430 (let ((snapshot (visit-snapshot visit)))
431 (match (and=> (find (lambda (branch)
432 (string=? (string-append "refs/tags/" tag)
433 (branch-name branch)))
434 (snapshot-branches snapshot))
435 branch-target)
436 ((? release? release)
437 (release-target release))
438 ((? revision? revision)
439 revision)
440 (#f ;tag not found
441 #f))))
442 (()
443 #f)))))
444
445(define (release-target release)
446 "Return the revision that is the target of RELEASE."
447 (match (release-target-type release)
448 ('revision
449 (call (swh-url (release-target-url release))
450 json->revision))))
451
452(define (directory-entry-target entry)
453 "If ENTRY, a directory entry, has type 'directory, return its list of
454directory entries; if it has type 'file, return its <content> object."
455 (call (swh-url (directory-entry-target-url entry))
456 (match (directory-entry-type entry)
457 ('file json->content)
458 ('directory json->directory-entries))))
459
460(define* (save-origin url #:optional (type "git"))
461 "Request URL to be saved."
462 (call (swh-url "/api/1/origin/save" type "url" url) json->save-reply
463 http-post))
464
465(define-query (save-origin-status url type)
466 "Return the status of a /save request for URL and TYPE (e.g., \"git\")."
467 (path "/api/1/origin/save" type "url" url)
468 json->save-reply)
469
470(define-query (query-vault id kind)
471 "Ask the availability of object ID and KIND to the vault, where KIND is
472'directory or 'revision. Return #f if it could not be found, or a
473<vault-reply> on success."
474 ;; <https://docs.softwareheritage.org/devel/swh-vault/api.html#vault-api-ref>
475 ;; There's a single format supported for directories and revisions and for
476 ;; now, the "/format" bit of the URL *must* be omitted.
477 (path "/api/1/vault" (symbol->string kind) id)
478 json->vault-reply)
479
480(define (request-cooking id kind)
481 "Request the cooking of object ID and KIND (one of 'directory or 'revision)
482to the vault. Return a <vault-reply>."
483 (call (swh-url "/api/1/vault" (symbol->string kind) id)
484 json->vault-reply
485 http-post))
486
487(define* (vault-fetch id kind
488 #:key (log-port (current-error-port)))
489 "Return an input port from which a bundle of the object with the given ID
490and KIND (one of 'directory or 'revision) can be retrieved, or #f if the
491object could not be found.
492
493For a directory, the returned stream is a gzip-compressed tarball. For a
494revision, it is a gzip-compressed stream for 'git fast-import'."
495 (let loop ((reply (query-vault id kind)))
496 (match reply
497 (#f
498 (and=> (request-cooking id kind) loop))
499 (_
500 (match (vault-reply-status reply)
501 ('done
502 ;; Fetch the bundle.
503 (let-values (((response port)
504 (http-get (swh-url (vault-reply-fetch-url reply))
505 #:streaming? #t)))
506 (if (= (response-code response) 200)
507 port
508 (begin ;shouldn't happen
509 (close-port port)
510 #f))))
511 ('failed
512 ;; Upon failure, we're supposed to try again.
513 (format log-port "SWH vault: failure: ~a~%"
514 (vault-reply-progress-message reply))
515 (format log-port "SWH vault: retrying...~%")
516 (loop (request-cooking id kind)))
517 ((and (or 'new 'pending) status)
518 ;; Wait until the bundle shows up.
519 (let ((message (vault-reply-progress-message reply)))
520 (when (eq? 'new status)
521 (format log-port "SWH vault: \
522requested bundle cooking, waiting for completion...~%"))
523 (when (string? message)
524 (format log-port "SWH vault: ~a~%" message))
525
526 ;; Wait long enough so we don't exhaust our maximum number of
527 ;; requests per hour too fast (as of this writing, the limit is 60
528 ;; requests per hour per IP address.)
529 (sleep (if (eq? status 'new) 60 30))
530
531 (loop (query-vault id kind)))))))))
532
533\f
534;;;
535;;; High-level interface.
536;;;
537
538(define (commit-id? reference)
539 "Return true if REFERENCE is likely a commit ID, false otherwise---e.g., if
d370cc73 540it is a tag name. This is based on a simple heuristic so use with care!"
de2bfe90
LC
541 (and (= (string-length reference) 40)
542 (string-every char-set:hex-digit reference)))
543
544(define (call-with-temporary-directory proc) ;FIXME: factorize
545 "Call PROC with a name of a temporary directory; close the directory and
546delete it when leaving the dynamic extent of this call."
547 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
548 (template (string-append directory "/guix-directory.XXXXXX"))
549 (tmp-dir (mkdtemp! template)))
550 (dynamic-wind
551 (const #t)
552 (lambda ()
553 (proc tmp-dir))
554 (lambda ()
555 (false-if-exception (delete-file-recursively tmp-dir))))))
556
b8815c5e
LC
557(define* (swh-download url reference output
558 #:key (log-port (current-error-port)))
de2bfe90
LC
559 "Download from Software Heritage a checkout of the Git tag or commit
560REFERENCE originating from URL, and unpack it in OUTPUT. Return #t on success
561and #f on failure.
562
563This procedure uses the \"vault\", which contains \"cooked\" directories in
564the form of tarballs. If the requested directory is not cooked yet, it will
565wait until it becomes available, which could take several minutes."
566 (match (if (commit-id? reference)
567 (lookup-revision reference)
568 (lookup-origin-revision url reference))
569 ((? revision? revision)
b8815c5e
LC
570 (format log-port "SWH: found revision ~a with directory at '~a'~%"
571 (revision-id revision)
572 (swh-url (revision-directory-url revision)))
de2bfe90
LC
573 (call-with-temporary-directory
574 (lambda (directory)
b8815c5e
LC
575 (match (vault-fetch (revision-directory revision) 'directory
576 #:log-port log-port)
90c98b5a 577 (#f
b8815c5e
LC
578 (format log-port
579 "SWH: directory ~a could not be fetched from the vault~%"
580 (revision-directory revision))
90c98b5a
LC
581 #f)
582 ((? port? input)
583 (let ((tar (open-pipe* OPEN_WRITE "tar" "-C" directory "-xzvf" "-")))
584 (dump-port input tar)
585 (close-port input)
586 (let ((status (close-pipe tar)))
587 (unless (zero? status)
588 (error "tar extraction failure" status)))
589
590 (match (scandir directory)
591 (("." ".." sub-directory)
592 (copy-recursively (string-append directory "/" sub-directory)
593 output
594 #:log (%make-void-port "w"))
595 #t))))))))
de2bfe90
LC
596 (#f
597 #f)))