swh.scm 22 KB

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