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