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