still_active 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +34 -0
  3. data/README.md +3 -1
  4. data/lib/still_active/artifactory_client.rb +2 -20
  5. data/lib/still_active/assessment.rb +85 -0
  6. data/lib/still_active/cli.rb +84 -23
  7. data/lib/still_active/config.rb +2 -0
  8. data/lib/still_active/deps_dev_client.rb +161 -15
  9. data/lib/still_active/diff.rb +38 -0
  10. data/lib/still_active/ecosystem_lens.rb +80 -44
  11. data/lib/still_active/ecosystems_client.rb +10 -7
  12. data/lib/still_active/errors.rb +10 -0
  13. data/lib/still_active/forgejo_client.rb +5 -1
  14. data/lib/still_active/github_client.rb +28 -5
  15. data/lib/still_active/gitlab_client.rb +5 -1
  16. data/lib/still_active/go_toolchain.rb +75 -0
  17. data/lib/still_active/helpers/alternatives_helper.rb +2 -2
  18. data/lib/still_active/helpers/cvss_helper.rb +14 -48
  19. data/lib/still_active/helpers/cyclonedx_helper.rb +7 -0
  20. data/lib/still_active/helpers/diff_markdown_helper.rb +5 -0
  21. data/lib/still_active/helpers/emoji_helper.rb +2 -1
  22. data/lib/still_active/helpers/endoflife_helper.rb +3 -2
  23. data/lib/still_active/helpers/http_cache.rb +109 -0
  24. data/lib/still_active/helpers/http_helper.rb +148 -28
  25. data/lib/still_active/helpers/markdown_helper.rb +1 -1
  26. data/lib/still_active/helpers/repository_check.rb +33 -0
  27. data/lib/still_active/helpers/status_helper.rb +11 -0
  28. data/lib/still_active/helpers/summary_helper.rb +6 -1
  29. data/lib/still_active/helpers/terminal_helper.rb +9 -1
  30. data/lib/still_active/helpers/vulnerability_helper.rb +4 -5
  31. data/lib/still_active/options.rb +7 -0
  32. data/lib/still_active/osv_client.rb +39 -2
  33. data/lib/still_active/repository_signals.rb +113 -0
  34. data/lib/still_active/rubygems_client.rb +34 -0
  35. data/lib/still_active/sarif/rules.rb +1 -1
  36. data/lib/still_active/sbom_workflow.rb +16 -2
  37. data/lib/still_active/source_health.rb +88 -0
  38. data/lib/still_active/version.rb +1 -1
  39. data/lib/still_active/workflow.rb +63 -52
  40. data/lib/still_active.rb +1 -0
  41. data/still_active.gemspec +6 -7
  42. metadata +13 -6
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "time"
4
4
  require "octokit"
5
+ require_relative "errors"
5
6
 
6
7
  module StillActive
7
8
  # Repo signals (archived?, last commit date) for github.com-hosted gems.
@@ -20,19 +21,37 @@ module StillActive
20
21
  # object's pushed_at (last push) stands in for the last-commit date: it
21
22
  # matches the default-branch commit date to the day in practice, and folding
22
23
  # the two signals into one call halves the per-gem GitHub requests. Returns
23
- # {} when the repo can't be read, so the caller leaves both signals blank.
24
+ # {} when GitHub says the repo doesn't exist; raises RepoAccessDenied when it
25
+ # refuses the token, and RepoSignalsUnavailable when it can't answer (a rate
26
+ # limit past its short wait, an error status, a network failure).
27
+ # RepositorySignals decides what to ask next.
24
28
  def repo_signals(owner:, name:)
25
29
  return {} if owner.nil? || name.nil?
26
30
 
27
31
  repo = with_rate_limit_retry("repo #{owner}/#{name}") do
28
32
  StillActive.config.github_client.repository("#{owner}/#{name}")
29
33
  end
30
- return {} unless repo
34
+ raise RepoSignalsUnavailable, "#{owner}/#{name}: rate limited" if repo == :rate_limited
31
35
 
32
36
  {archived: repo.archived, last_commit_date: as_time(repo.pushed_at, owner, name)}
37
+ rescue Octokit::NotFound
38
+ {}
39
+ # Permanent "don't know", like a 404: a name Octokit refuses up front (an
40
+ # ArgumentError), a repository GitHub has blocked, or one withheld for legal
41
+ # reasons. A rerun won't change them, so they're not a failure.
42
+ rescue Octokit::InvalidRepository, Octokit::RepositoryUnavailable, Octokit::UnavailableForLegalReasons
43
+ {}
44
+ # Rate limits are Forbidden subclasses in Octokit (a 403), but they say
45
+ # nothing about the repository being private, so they don't stop the chain.
46
+ rescue Octokit::TooManyRequests, Octokit::AbuseDetected, Octokit::TooManyLoginAttempts => e
47
+ warn("warning: repo signals failed for #{owner}/#{name}: #{e.class}")
48
+ raise RepoSignalsUnavailable, "#{owner}/#{name}: #{e.class}"
49
+ rescue Octokit::Unauthorized, Octokit::Forbidden => e
50
+ warn("warning: repo signals failed for #{owner}/#{name}: #{e.class}")
51
+ raise RepoAccessDenied, "#{owner}/#{name}: #{e.class}"
33
52
  rescue Octokit::Error, Faraday::Error => e
34
53
  warn("warning: repo signals failed for #{owner}/#{name}: #{e.class}")
35
- {}
54
+ raise RepoSignalsUnavailable, "#{owner}/#{name}: #{e.class}"
36
55
  end
37
56
 
38
57
  # Commits on the default branch since the latest release's tag: the
@@ -48,7 +67,8 @@ module StillActive
48
67
 
49
68
  repo = "#{owner}/#{name}"
50
69
  ["v#{version}", version.to_s].each do |tag|
51
- return with_rate_limit_retry("unreleased-commits #{repo}") { StillActive.config.github_client.compare(repo, tag, "HEAD").ahead_by }
70
+ ahead = with_rate_limit_retry("unreleased-commits #{repo}") { StillActive.config.github_client.compare(repo, tag, "HEAD").ahead_by }
71
+ return (ahead == :rate_limited) ? nil : ahead
52
72
  rescue Octokit::NotFound
53
73
  # this tag form doesn't exist; fall through to try the next one
54
74
  end
@@ -60,6 +80,9 @@ module StillActive
60
80
 
61
81
  private
62
82
 
83
+ # Only an answer that says whether the repo is archived counts: ecosyste.ms
84
+ # 404s a repo it hasn't crawled, and after GitHub failed that is nobody
85
+ # answering.
63
86
  # Pause-and-retry on a rate-limit response when the reset is near, so a
64
87
  # transient secondary/burst limit (which GitHub's concurrent fan-out can
65
88
  # trip even with a token) self-heals instead of dropping the gem's signal.
@@ -76,7 +99,7 @@ module StillActive
76
99
  # Surface the one actionable hint rather than a generic class name,
77
100
  # then return nil so this signal is simply absent for the gem.
78
101
  warn("rate limited on #{label}; set GITHUB_TOKEN to raise your limit, or run less often")
79
- return
102
+ return :rate_limited
80
103
  end
81
104
 
82
105
  retried = true
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "time"
4
+ require_relative "errors"
4
5
  require_relative "helpers/http_helper"
5
6
 
6
7
  module StillActive
@@ -17,10 +18,13 @@ module StillActive
17
18
  return {} if owner.nil? || name.nil?
18
19
 
19
20
  path = "/api/v4/projects/#{encode_project(owner, name)}"
20
- body = HttpHelper.get_json(BASE_URI, path, headers: auth_headers)
21
+ # {} for a 404 (an answer); RepoSignalsUnavailable when GitLab couldn't answer.
22
+ body = HttpHelper.get_json(BASE_URI, path, headers: auth_headers, strict: true)
21
23
  return {} if body.nil?
22
24
 
23
25
  {archived: body["archived"] == true, last_commit_date: parse_time(body["last_activity_at"], owner, name)}
26
+ rescue HttpHelper::Unavailable => e
27
+ raise RepoSignalsUnavailable, e.message
24
28
  end
25
29
 
26
30
  private
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "osv_client"
4
+ require_relative "helpers/endoflife_helper"
5
+
6
+ module StillActive
7
+ # The Go toolchain, which Syft emits as the module `stdlib` (pkg:golang/stdlib@1.27.1).
8
+ # It is a runtime, and deps.dev can't serve it: it keys versions `go1.27.1` so the
9
+ # purl's version 404s, its index stops at go1.25.5, and its advisory list is the same
10
+ # for every version (verified 2026-09-24). So the release lines come from
11
+ # endoflife.date and the advisories from OSV by version, the sources the Ruby
12
+ # runtime check already trusts.
13
+ module GoToolchain
14
+ extend self
15
+
16
+ MODULE = "stdlib"
17
+
18
+ def toolchain?(ecosystem, name)
19
+ ecosystem == :go && name == MODULE
20
+ end
21
+
22
+ # Syft writes 1.27.1, a component version often go1.27.1, Trivy v1.27.1.
23
+ def release(version)
24
+ version.to_s.delete_prefix("go").delete_prefix("v")
25
+ end
26
+
27
+ # The same { info:, default:, vulnerabilities:, vulnerabilities_checked:,
28
+ # project_id:, version_unresolved: }
29
+ # EcosystemLens builds from deps.dev for any other package.
30
+ def signals(version:)
31
+ release = release(version)
32
+ cycles = EndoflifeHelper.fetch_cycles("/api/go.json")
33
+ cycles = nil unless cycles.is_a?(Array) && cycles.all?(Hash) && !cycles.empty?
34
+ latest = cycles&.first
35
+ cycle = cycles&.find { |c| c["cycle"] == release.split(".").first(2).join(".") }
36
+ # Only a plain release (1.20 and earlier shipped as go1.20): OSV writes Go
37
+ # prereleases as 1.27.0-rc.1, so a `1.27rc1` query would come back empty and
38
+ # read as clean.
39
+ vulnerabilities = OsvClient.advisories(ecosystem: :go, name: MODULE, version: release) if release.match?(/\A\d+\.\d+(\.\d+)?\z/)
40
+ warn("warning: go/#{MODULE}@#{release} advisories not checked (not a plain release, or OSV gave no complete answer); treat it as unknown, not clean") if vulnerabilities.nil?
41
+
42
+ {
43
+ info: cycle && {published_at: release_date(cycle, release), licenses: [], **end_of_life(cycle, latest)},
44
+ default: latest && {version: latest["latest"], published_at: latest["latestReleaseDate"]},
45
+ vulnerabilities: vulnerabilities || [],
46
+ vulnerabilities_checked: !vulnerabilities.nil?,
47
+ project_id: nil,
48
+ # The feed is up but doesn't know this release line.
49
+ version_unresolved: !cycles.nil? && cycle.nil?
50
+ }
51
+ end
52
+
53
+ private
54
+
55
+ # The feed dates each line's first and latest release only.
56
+ def release_date(cycle, release)
57
+ if release == cycle["latest"]
58
+ cycle["latestReleaseDate"]
59
+ elsif [cycle["cycle"], "#{cycle["cycle"]}.0"].include?(release)
60
+ cycle["releaseDate"]
61
+ end
62
+ end
63
+
64
+ # Go supports its two newest lines. Past that the Go team has said a line gets no
65
+ # more fixes, which is the maintainer's deprecation this field already carries.
66
+ def end_of_life(cycle, latest)
67
+ return {deprecated: false, deprecation_reason: nil} unless EndoflifeHelper.eol_reached?(cycle["eol"])
68
+
69
+ # Worded as what the Go team did, since output labels it the maintainer's note.
70
+ on = EndoflifeHelper.parse_eol(cycle["eol"])&.strftime(" on %Y-%m-%d")
71
+ upgrade = latest && " Upgrade to #{latest["latest"]}."
72
+ {deprecated: true, deprecation_reason: "The Go team ended the #{cycle["cycle"]} release line#{on}; it gets no further security fixes.#{upgrade}"}
73
+ end
74
+ end
75
+ end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "gems"
3
+ require_relative "../rubygems_client"
4
4
 
5
5
  module StillActive
6
6
  # Turns a gem's catalog siblings into ranked "leads" -- the most-downloaded
@@ -33,7 +33,7 @@ module StillActive
33
33
  private
34
34
 
35
35
  def downloads(gem_name)
36
- info = Gems.info(gem_name)
36
+ info = RubygemsClient.info(gem_name)
37
37
  info && info["downloads"]
38
38
  rescue
39
39
  nil
@@ -1,63 +1,29 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "cvss_suite"
4
+
3
5
  module StillActive
4
- # Computes a CVSS score from a vector string, across v2/v3/v4. deps.dev stores only
5
- # CVSS 3.x, so a CVSS-4-only advisory (the flagship protobuf case) arrives with no
6
- # numeric score; OSV carries the v4 vector, and this turns it into the number the
6
+ # Computes a CVSS base score from a vector string, across v2/v3/v4. deps.dev stores
7
+ # only CVSS 3.x, so a CVSS-4-only advisory (the flagship protobuf case) arrives with
8
+ # no numeric score; OSV carries the v4 vector, and this turns it into the number the
7
9
  # SARIF security-severity and CycloneDX rating want.
8
10
  #
9
- # cvss-suite is an OPTIONAL, undeclared dependency: it over-constrains its own deps
10
- # (an exact `bundler` pin, a `bigdecimal ~> 3.1` cap), the poison-pill pattern
11
- # still_active itself flags, so hard-requiring it would force that liability on every
12
- # user and trip our own audit. CvssHelper soft-requires it; install cvss-suite (or run
13
- # the distribution that bundles it) to light it up.
14
- #
15
- # Returns cvss-suite's `overall_score`: for the base-only vectors OSV publishes that
16
- # IS the base score, but a vector carrying threat/environmental metrics would fold
17
- # those in -- which is why the severity band floors at the authoritative GHSA label
18
- # (VulnerabilityHelper.advisory_severity) and this number never lowers it: the label
19
- # drives gating and SARIF level, the number only sharpens display. Fails safe: an
20
- # absent gem or an absent/unparseable vector yields nil, never a crash.
11
+ # Returns the BASE score, not cvss-suite's overall_score: a vector carrying threat or
12
+ # environmental metrics folds those into overall_score (E:U alone turns a 9.3 into
13
+ # an 8.1), while NVD and GHSA publish the base score. The severity band still floors
14
+ # at the authoritative GHSA label (VulnerabilityHelper.advisory_severity) because
15
+ # labels are assigned by people and can sit off the FIRST band edge; the label drives
16
+ # gating and SARIF level, the number sharpens display. Fails safe: an absent or
17
+ # unparseable vector yields nil, never a crash.
21
18
  module CvssHelper
22
19
  extend self
23
20
 
24
21
  def score(vector)
25
- return unless available?
26
22
  return if vector.nil? || vector.to_s.empty?
27
23
 
28
- cvss = CvssSuite.new(vector.to_s)
29
- cvss.valid? ? cvss.overall_score : nil
30
- rescue => e
31
- # We only reach here with cvss-suite loaded (available?), so a raise is the
32
- # installed gem failing this call site -- an incompatible version, a renamed
33
- # `overall_score` -- not a bad vector, which cvss-suite reports via valid?.
34
- # Fail safe to nil (the number is display-only, never gates), but don't
35
- # swallow it: an opted-in-but-broken scorer that emitted nothing would read
36
- # as "no advisories are scored". Warn once per run (not per advisory),
37
- # matching OsvClient.enrich rather than staying silent.
38
- warn_scorer_failed(e)
24
+ CvssSuite.parse(vector.to_s).base_score
25
+ rescue CvssSuite::Error
39
26
  nil
40
27
  end
41
-
42
- # Memoized soft-require: true once cvss-suite loads, false when it isn't installed.
43
- def available?
44
- return @available unless @available.nil?
45
-
46
- @available = begin
47
- require "cvss_suite"
48
- true
49
- rescue LoadError
50
- false
51
- end
52
- end
53
-
54
- private
55
-
56
- def warn_scorer_failed(error)
57
- return if @warned
58
-
59
- @warned = true
60
- warn("warning: cvss-suite scoring failed: #{error.class} (#{error.message}); CVSS numbers unavailable this run, check your cvss-suite version")
61
- end
62
28
  end
63
29
  end
@@ -6,6 +6,7 @@ require "time"
6
6
  require_relative "activity_helper"
7
7
  require_relative "status_helper"
8
8
  require_relative "vulnerability_helper"
9
+ require_relative "repository_check"
9
10
 
10
11
  module StillActive
11
12
  # Renders a still_active workflow result as a CycloneDX SBOM. Emits 1.6 by
@@ -152,6 +153,12 @@ module StillActive
152
153
  "still_active:archived" => boolean_property(data[:archived]),
153
154
  "still_active:deprecated" => boolean_property(data[:deprecated]),
154
155
  "still_active:deprecation_reason" => data[:deprecation_reason],
156
+ # An empty vulnerabilities list reads as clean downstream; this says whether
157
+ # anything was actually looked up.
158
+ "still_active:vulnerabilities_checked" => boolean_property(data[:vulnerabilities_checked]),
159
+ # Present only when no service answered: a blank archived flag here is
160
+ # "unknown", not "no".
161
+ "still_active:repository_check" => (RepositoryCheck.unanswered?(data) ? data[:repository_check] : nil),
155
162
  "still_active:scorecard_score" => data[:scorecard_score]&.to_s,
156
163
  "still_active:libyear" => data[:libyear]&.to_s,
157
164
  "still_active:last_commit_date" => iso8601(data[:last_commit_date])
@@ -12,6 +12,7 @@ module StillActive
12
12
 
13
13
  BUMP_KIND_LABELS = {
14
14
  closed_vulns: "closed vulns",
15
+ advisories_unchecked: "advisories UNCHECKED",
15
16
  introduced_vulns: "INTRODUCED vulns",
16
17
  fresher: "fresher",
17
18
  older_relative: "older relative to latest",
@@ -149,6 +150,10 @@ module StillActive
149
150
  "- #{name} — scorecard #{MarkdownEscape.inline(ch[:from])} → #{MarkdownEscape.inline(ch[:to])}#{note}"
150
151
  when :version_yanked
151
152
  "- #{name} — version yanked from rubygems"
153
+ when :advisories_unchecked
154
+ "- #{name} — advisories could not be checked"
155
+ when :repository_unchecked
156
+ "- #{name} — repository no longer checked (#{MarkdownEscape.inline(ch[:check])}; may be archived)"
152
157
  when :libyear_worsened
153
158
  "- #{name} — libyear #{MarkdownEscape.inline(ch[:from])} → #{MarkdownEscape.inline(ch[:to])} (+#{ch[:delta]}y; same pinned version)"
154
159
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "activity_helper"
4
+ require_relative "repository_check"
4
5
 
5
6
  module StillActive
6
7
  module EmojiHelper
@@ -8,7 +9,7 @@ module StillActive
8
9
 
9
10
  def inactive_gem_emoji(result_hash)
10
11
  case ActivityHelper.activity_level(result_hash)
11
- when :ok then ""
12
+ when :ok then RepositoryCheck.unanswered?(result_hash) ? StillActive.config.unsure_emoji : ""
12
13
  when :stale then StillActive.config.warning_emoji
13
14
  when :archived, :critical then StillActive.config.critical_warning_emoji
14
15
  when :unknown then StillActive.config.unsure_emoji
@@ -87,12 +87,13 @@ module StillActive
87
87
  end
88
88
  end
89
89
 
90
- private
91
-
90
+ # The feed's raw cycles, newest first, or nil when it's unavailable.
92
91
  def fetch_cycles(feed_path)
93
92
  HttpHelper.get_json(ENDOFLIFE_URI, feed_path)
94
93
  end
95
94
 
95
+ private
96
+
96
97
  def normalize_cycle(cycle)
97
98
  version = cycle["cycle"]
98
99
  return unless version && Gem::Version.correct?(version)
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "json"
6
+
7
+ module StillActive
8
+ # An on-disk cache of public sources' JSON answers, so a rerun, or the baseline
9
+ # and current audits of one CI job, don't ask for the same thing twice. Only the
10
+ # hosts and paths in RULES are cached, each for as long as that data can be
11
+ # trusted to hold: an answer that carries advisories for an hour, so a new CVE
12
+ # is at most an hour late (--no-cache for none), a published version's record
13
+ # for a week, since it doesn't change. Nothing credentialed is cached: those
14
+ # hosts aren't listed, and a request with an Authorization header is skipped
15
+ # whatever its host. Failures and 404s aren't cached, only answers.
16
+ #
17
+ # OSV's version query is deliberately absent. It is the arbiter that drops a
18
+ # deps.dev finding the version isn't affected by, so it must never be older
19
+ # than the deps.dev record it judges; cached separately, it could be, and would
20
+ # drop an advisory published after it was cached.
21
+ module HttpCache
22
+ extend self
23
+
24
+ HOUR = 60 * 60
25
+ DAY = 24 * HOUR
26
+ WEEK = 7 * DAY
27
+
28
+ # [host, path pattern, seconds], first match wins.
29
+ RULES = [
30
+ ["api.deps.dev", %r{\A/v3alpha/systems/[^/]+/packages/[^/]+/versions/[^/]+:requirements\z}, WEEK],
31
+ ["api.deps.dev", %r{\A/v3alpha/systems/[^/]+/packages/[^/]+/versions/}, HOUR], # carries advisoryKeys
32
+ ["api.deps.dev", %r{\A/v3alpha/systems/[^/]+/packages/[^/]+\z}, 6 * HOUR], # latest version
33
+ ["api.deps.dev", %r{\A/v3alpha/advisories/}, 6 * HOUR], # CVSS, which the severity gates read
34
+ ["api.deps.dev", %r{\A/v3alpha/projects/}, DAY],
35
+ ["api.osv.dev", %r{\A/v1/vulns/}, 6 * HOUR], # severity and fixed versions
36
+ ["rubygems.org", %r{\A/api/v1/versions/}, 6 * HOUR],
37
+ ["rubygems.org", %r{\A/api/v1/gems/}, DAY],
38
+ ["pypi.org", %r{\A/pypi/[^/]+/[^/]+/json\z}, WEEK], # one published version
39
+ ["packages.ecosyste.ms", %r{/versions/}, WEEK], # one published version's declared deps
40
+ ["repos.ecosyste.ms", %r{\A/api/v1/hosts/}, DAY],
41
+ ["endoflife.date", %r{\A/api/}, DAY]
42
+ ].freeze
43
+
44
+ # Entries older than any rule allows are deleted when the cache is first used.
45
+ MAX_AGE = WEEK
46
+
47
+ # Seconds to cache this request's answer for, or nil to not cache it.
48
+ def ttl(uri, headers)
49
+ return unless StillActive.config.http_cache
50
+ return if headers.keys.any? { _1.to_s.casecmp?("Authorization") }
51
+
52
+ RULES.find { |host, pattern, _| uri.host == host && uri.path.match?(pattern) }&.last
53
+ end
54
+
55
+ # The cached answer, or :miss.
56
+ def read(key, ttl)
57
+ path = path_for(key)
58
+ return :miss unless File.exist?(path)
59
+
60
+ entry = JSON.parse(File.read(path))
61
+ age = Time.now.to_f - entry.fetch("stored_at")
62
+ # A future stamp (clock skew, a cache restored from another machine) would
63
+ # otherwise never expire.
64
+ return :miss if age.negative? || age > ttl
65
+
66
+ entry.fetch("body")
67
+ rescue JSON::ParserError, KeyError, TypeError, SystemCallError
68
+ :miss
69
+ end
70
+
71
+ # Best-effort: a cache that can't be written is just a cache miss next time.
72
+ def write(key, body)
73
+ sweep_once
74
+ path = path_for(key)
75
+ FileUtils.mkdir_p(File.dirname(path))
76
+ temp = "#{path}.#{Process.pid}.#{rand(1 << 32)}.tmp"
77
+ File.write(temp, JSON.generate({"stored_at" => Time.now.to_f, "body" => body}))
78
+ File.rename(temp, path)
79
+ rescue SystemCallError, IOError
80
+ File.delete(temp) if temp && File.exist?(temp)
81
+ end
82
+
83
+ def key(method, uri)
84
+ Digest::SHA256.hexdigest("#{method}\n#{uri}")
85
+ end
86
+
87
+ def directory
88
+ base = ENV["XDG_CACHE_HOME"]
89
+ base = File.join(Dir.home, ".cache") if base.nil? || base.empty?
90
+ File.join(base, "still_active", "http")
91
+ end
92
+
93
+ private
94
+
95
+ def path_for(key)
96
+ File.join(directory, key[0, 2], "#{key}.json")
97
+ end
98
+
99
+ def sweep_once
100
+ return if @swept
101
+
102
+ @swept = true
103
+ cutoff = Time.now - MAX_AGE
104
+ Dir.glob(File.join(directory, "*", "*.{json,tmp}")).each { File.delete(_1) if File.mtime(_1) < cutoff }
105
+ rescue SystemCallError
106
+ nil
107
+ end
108
+ end
109
+ end