collavre_github 0.6.3 → 0.8.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 (38) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/collavre_github/creatives/integrations_controller.rb +253 -36
  3. data/app/controllers/collavre_github/webhooks_controller.rb +563 -44
  4. data/app/javascript/collavre_github.js +32 -123
  5. data/app/jobs/collavre_github/initial_markdown_sync_job.rb +6 -4
  6. data/app/jobs/collavre_github/markdown_sync_job.rb +6 -4
  7. data/app/jobs/collavre_github/pr_blocker_sweep_job.rb +18 -0
  8. data/app/jobs/collavre_github/webhook_delivery_prune_job.rb +14 -0
  9. data/app/models/collavre_github/github_pr_channel.rb +124 -28
  10. data/app/models/collavre_github/repository_link.rb +63 -2
  11. data/app/models/collavre_github/webhook_delivery.rb +159 -0
  12. data/app/services/collavre_github/client.rb +37 -0
  13. data/app/services/collavre_github/markdown_sync/content_creative.rb +56 -0
  14. data/app/services/collavre_github/markdown_sync/content_processor.rb +16 -1
  15. data/app/services/collavre_github/markdown_sync/incremental_sync_service.rb +12 -34
  16. data/app/services/collavre_github/markdown_sync/initial_import_service.rb +6 -19
  17. data/app/services/collavre_github/pr_blocker_monitor.rb +93 -0
  18. data/app/services/collavre_github/pr_channel_state_updater.rb +83 -0
  19. data/app/services/collavre_github/pr_discussion_event.rb +25 -0
  20. data/app/services/collavre_github/repository_identity_synchronizer.rb +145 -0
  21. data/app/services/collavre_github/repository_provisioning_lock.rb +95 -0
  22. data/app/services/collavre_github/tools/concerns/pr_channel_locator.rb +50 -0
  23. data/app/services/collavre_github/tools/pr_monitor_service.rb +82 -62
  24. data/app/services/collavre_github/tools/pr_state_set_service.rb +170 -0
  25. data/app/services/collavre_github/webhook_provisioner.rb +601 -42
  26. data/app/services/collavre_github/webhook_reprovisioner.rb +118 -0
  27. data/config/locales/en.yml +4 -0
  28. data/config/locales/ko.yml +4 -0
  29. data/config/locales/tool_descriptions.en.yml +20 -0
  30. data/config/locales/tool_descriptions.ko.yml +20 -0
  31. data/config/routes.rb +13 -3
  32. data/db/migrate/20260727000001_add_webhook_hook_id_to_github_repository_links.rb +17 -0
  33. data/db/migrate/20260727000002_create_github_webhook_deliveries.rb +30 -0
  34. data/db/migrate/20260729000000_add_repository_id_index_to_github_repository_links.rb +13 -0
  35. data/db/seeds.rb +2 -1
  36. data/lib/collavre_github/engine.rb +9 -0
  37. data/lib/collavre_github/version.rb +1 -1
  38. metadata +19 -2
@@ -7,8 +7,8 @@ module CollavreGithub
7
7
  belongs_to :markdown_root_creative, class_name: "Collavre::Creative", optional: true
8
8
 
9
9
  # HMAC secret GitHub signs webhook deliveries with. Encrypted at rest so a
10
- # DB/backup leak can't forge webhooks (mirrors CollavreGithub::Account#token
11
- # and CollavreLinear::ProjectLink#webhook_secret). Non-deterministic: the
10
+ # DB/backup leak can't forge webhooks (mirrors CollavreGithub::Account#token).
11
+ # Non-deterministic: the
12
12
  # value is only ever read back decrypted (WebhooksController, provisioner),
13
13
  # never queried by ciphertext. A backfill migration re-encrypts pre-existing
14
14
  # plaintext rows.
@@ -21,6 +21,67 @@ module CollavreGithub
21
21
 
22
22
  scope :markdown_sync, -> { where(markdown_sync_enabled: true) }
23
23
 
24
+ # Every link for one GitHub repository, matched by its stable id plus
25
+ # unbackfilled name-only siblings.
26
+ #
27
+ # `repository_full_name` is the only key webhook routing used to have, and
28
+ # it is not stable: renaming a repository on GitHub changes `full_name` in
29
+ # every subsequent payload with no local event to notice it. The lookup
30
+ # then found nothing, the controller fell through to a fallback secret that
31
+ # production does not configure, and every delivery was answered 401 before
32
+ # dispatch — silently, since the deliveries ledger is only written after
33
+ # signature verification. `repository.id` does survive a rename, which is
34
+ # why it is matched first-class here.
35
+ #
36
+ # When an id is present, name matching is restricted to NULL-id rows. A
37
+ # repository linked to two creatives can be half-backfilled (one row
38
+ # stamped, its sibling still nil), so those legacy siblings must remain in
39
+ # the fan-out. Rows carrying another id are authoritative links to another
40
+ # repository, even when GitHub has reused their stored name.
41
+ def self.for_repository(id:, full_name:)
42
+ name = full_name.to_s.downcase.presence
43
+ if id.present?
44
+ by_id = where(repository_id: id)
45
+ return by_id unless name
46
+
47
+ unbackfilled_by_name = where(repository_id: nil)
48
+ .where("LOWER(repository_full_name) = ?", name)
49
+ return by_id.or(unbackfilled_by_name)
50
+ end
51
+
52
+ name ? where("LOWER(repository_full_name) = ?", name) : none
53
+ end
54
+
55
+ # A parent link normally applies to every descendant, but a descendant may
56
+ # carry its own link for another repository that reused the same name. An
57
+ # explicit different id proves the conflict; a NULL id is unverified and
58
+ # must fail closed. In either case, the descendant's channels must not be
59
+ # renamed through the parent.
60
+ def self.conflicting_repository_in_scope?(creative:, full_name:, repository_id:)
61
+ return false if creative.blank? || full_name.blank? || repository_id.blank?
62
+
63
+ creative_ids = [ creative.id ] + creative.ancestors.pluck(:id)
64
+ where(creative_id: creative_ids)
65
+ .where("LOWER(repository_full_name) = ?", full_name.to_s.downcase)
66
+ .where("repository_id IS NULL OR repository_id <> ?", repository_id)
67
+ .exists?
68
+ end
69
+
70
+ # Link mutations affect the link's whole descendant subtree, while an
71
+ # ancestor link is inherited into the same scope. Before assigning a
72
+ # canonical name, reject any NULL/different-id row in either direction so
73
+ # case variants cannot leave both repositories permanently undispatchable.
74
+ def self.identity_conflict_in_link_scope(creative:, full_name:, repository_id:, excluding_id: nil)
75
+ return if creative.blank? || full_name.blank? || repository_id.blank?
76
+
77
+ creative_ids = creative.subtree_ids + creative.ancestors.pluck(:id)
78
+ candidates = where(creative_id: creative_ids)
79
+ .where("LOWER(repository_full_name) = ?", full_name.to_s.downcase)
80
+ .where("repository_id IS NULL OR repository_id <> ?", repository_id)
81
+ candidates = candidates.where.not(id: excluding_id) if excluding_id
82
+ candidates.order(:id).first
83
+ end
84
+
24
85
  def markdown_sync_branch
25
86
  sync_branch.presence || "main"
26
87
  end
@@ -0,0 +1,159 @@
1
+ module CollavreGithub
2
+ # Idempotency ledger for inbound GitHub webhook deliveries, keyed by the
3
+ # `X-GitHub-Delivery` GUID.
4
+ #
5
+ # Two independent duplicate sources exist and both reuse the same GUID:
6
+ # 1. Multiple hooks on one repo (e.g. one per deployed instance sharing this
7
+ # database) — GitHub fans the same delivery out to every hook URL. This
8
+ # is what makes two hooks a bandwidth cost rather than the duplicate
9
+ # processing this ledger exists to stop, so it is load-bearing. The
10
+ # reference docs do state it, in one word that is easy to read past:
11
+ # `X-GitHub-Delivery` identifies "the event", not the delivery, so every
12
+ # destination subscribed to one event receives the same value and
13
+ # `X-GitHub-Hook-ID` is what differs. That wording read "the delivery"
14
+ # until github/docs#33184 corrected it (2024-05-27), after a GitHub
15
+ # engineer confirmed on github/docs#32822 that one event fans out to
16
+ # every listener under a single GUID.
17
+ # 2. Redelivery of a failed delivery. Never automatic: GitHub does not
18
+ # retry a 4xx, a 5xx or a >10s timeout, it only records the failure.
19
+ # Recovery is an operator pressing Redeliver or a script polling the
20
+ # deliveries API, within GitHub's 3-day window — and either way the
21
+ # original GUID comes back, which is what brings it here.
22
+ # A single UNIQUE claim on the GUID collapses both.
23
+ class WebhookDelivery < ApplicationRecord
24
+ self.table_name = "github_webhook_deliveries"
25
+
26
+ # Rows only exist to answer "have I seen this GUID?" — an updated_at column
27
+ # would never be written.
28
+ self.record_timestamps = false
29
+
30
+ # Sized against GitHub's redelivery window, which is 3 days: a delivery
31
+ # older than that can no longer be redelivered at all, so its row can never
32
+ # be consulted again. 7 days keeps better than 2x margin. Pruning EARLIER
33
+ # than the window would be the dangerous direction — the GUID would be
34
+ # claimed as new and every side effect would run a second time.
35
+ # https://docs.github.com/en/webhooks/testing-and-troubleshooting-webhooks/redelivering-webhooks
36
+ RETENTION = 7.days
37
+
38
+ # How long a claim may sit unprocessed before another delivery of the same
39
+ # GUID is allowed to take it over. `WebhooksController` releases its claim
40
+ # on any exception the process survives, so this window only covers a
41
+ # request that died without running its rescue — SIGKILL, an OOM, a worker
42
+ # timeout. Without the takeover such a GUID would answer 200 forever and
43
+ # the operator's Redeliver button would silently do nothing.
44
+ STALE_CLAIM_AFTER = 5.minutes
45
+
46
+ validates :delivery_guid, presence: true
47
+
48
+ # Claims the delivery for this process. Returns an ownership token when the
49
+ # caller owns the delivery and should process it, nil when another request
50
+ # (another hook, or a redelivery) already claimed it.
51
+ #
52
+ # The token, not the GUID, is what `release` and `mark_processed!` act on.
53
+ # Ownership is not permanent — a run that outlives STALE_CLAIM_AFTER has its
54
+ # claim taken over — so a caller that acted on the GUID alone would reach
55
+ # past its own claim and disturb the run that replaced it.
56
+ #
57
+ # A blank GUID means the request did not come from GitHub's delivery
58
+ # pipeline (hand-crafted request, legacy test client). There is nothing to
59
+ # deduplicate on, so it is allowed through rather than silently dropped —
60
+ # dropping would turn every unlabelled delivery into a no-op. UNTRACKED
61
+ # keeps the caller's contract uniform: it is truthy, and the GUID-blank
62
+ # guard in `release`/`mark_processed!` makes both a no-op for it.
63
+ UNTRACKED = "untracked".freeze
64
+
65
+ def self.claim(delivery_guid, event: nil)
66
+ return UNTRACKED if delivery_guid.blank?
67
+
68
+ insert_claim(delivery_guid, event)
69
+ end
70
+
71
+ # Resolves a collision on the UNIQUE index. Three things can be true of the
72
+ # row that beat us to it:
73
+ #
74
+ # - it is stale, and `reclaim_stale` takes it over;
75
+ # - it is live, so this delivery genuinely is a duplicate;
76
+ # - it is GONE, because the request holding it failed and called
77
+ # `release` between our INSERT and this lookup. Reporting a duplicate
78
+ # then would lose the event outright — that request has already given
79
+ # up, so nobody would process it — which is the very outcome the
80
+ # ledger exists to prevent. The insert is retried instead.
81
+ #
82
+ # One retry suffices: it only has to cover the window opened by that single
83
+ # release, and bounding it keeps a pathological loop of releases from
84
+ # spinning here forever.
85
+ def self.insert_claim(delivery_guid, event, retried: false)
86
+ token = SecureRandom.uuid
87
+ create!(
88
+ delivery_guid: delivery_guid,
89
+ event: event,
90
+ claim_token: token,
91
+ created_at: Time.current
92
+ )
93
+ token
94
+ rescue ActiveRecord::RecordNotUnique
95
+ reclaimed = reclaim_stale(delivery_guid, event: event)
96
+ return reclaimed if reclaimed
97
+ return nil if retried || exists?(delivery_guid: delivery_guid)
98
+
99
+ insert_claim(delivery_guid, event, retried: true)
100
+ end
101
+ private_class_method :insert_claim
102
+
103
+ # Takes over an abandoned claim. A row on its own does not prove the
104
+ # delivery was handled — only `processed_at` does — so an unprocessed row
105
+ # older than STALE_CLAIM_AFTER is treated as owner-less.
106
+ #
107
+ # Concurrent takeovers resolve to one winner without extra locking: the
108
+ # UPDATE takes a row lock, and the loser re-evaluates its WHERE against the
109
+ # committed row, whose `created_at` is no longer stale, so it matches
110
+ # nothing and reports the delivery as a duplicate.
111
+ #
112
+ # The takeover issues a FRESH token, which is what strips ownership from the
113
+ # run being replaced: its own `release`/`mark_processed!` no longer match.
114
+ def self.reclaim_stale(delivery_guid, event: nil)
115
+ token = SecureRandom.uuid
116
+ updated = where(delivery_guid: delivery_guid, processed_at: nil)
117
+ .where(created_at: ...STALE_CLAIM_AFTER.ago)
118
+ .update_all(created_at: Time.current, event: event, claim_token: token)
119
+
120
+ token if updated.positive?
121
+ end
122
+
123
+ # Marks a claim as genuinely handled. Only after this does a redelivery of
124
+ # the same GUID get dismissed as a duplicate.
125
+ #
126
+ # Scoped to the token: if this run was superseded while it worked, the row
127
+ # now belongs to its replacement and must not be stamped processed on its
128
+ # behalf — the replacement is still running and has yet to earn that.
129
+ def self.mark_processed!(delivery_guid, token)
130
+ return if delivery_guid.blank? || token.blank?
131
+
132
+ where(delivery_guid: delivery_guid, claim_token: token)
133
+ .update_all(processed_at: Time.current)
134
+ end
135
+
136
+ # Drops a claim whose run failed so the redelivery is processed instead of
137
+ # dismissed.
138
+ #
139
+ # Scoped to the token as well as to unprocessed rows. Unprocessed alone was
140
+ # not enough: a run slower than STALE_CLAIM_AFTER has already lost the row
141
+ # to a replacement, and deleting on the GUID would have taken the
142
+ # replacement's live claim with it — freeing the GUID for a third request
143
+ # to claim while the replacement was still running, and leaving the
144
+ # replacement's own `mark_processed!` with no row to stamp, so every later
145
+ # redelivery would repeat the event.
146
+ def self.release(delivery_guid, token)
147
+ return if delivery_guid.blank? || token.blank?
148
+
149
+ where(delivery_guid: delivery_guid, claim_token: token, processed_at: nil).delete_all
150
+ end
151
+
152
+ # Called from the recurring prune job. Past RETENTION the delivery has aged
153
+ # out of GitHub's 3-day Redeliver window, so nothing can reuse the GUID and
154
+ # the row only grows the table.
155
+ def self.prune!(older_than: RETENTION.ago)
156
+ where(created_at: ...older_than).delete_all
157
+ end
158
+ end
159
+ end
@@ -1,6 +1,7 @@
1
1
  module CollavreGithub
2
2
  class Client
3
3
  MOCK_SERVER_DEFAULT = "http://localhost:4567"
4
+ RepositoryIdentity = Data.define(:id, :full_name)
4
5
 
5
6
  def initialize(account)
6
7
  options = { access_token: account.token }
@@ -38,6 +39,29 @@ module CollavreGithub
38
39
  nil
39
40
  end
40
41
 
42
+ def pull_request_discussion(repo_full_name, endpoint)
43
+ client.paginate("repos/#{repo_full_name}/#{endpoint}").map { |item| item.to_h.deep_stringify_keys }
44
+ rescue Octokit::Error, Faraday::Error => e
45
+ Rails.logger.warn("GitHub PR discussion fetch failed: #{e.class}")
46
+ []
47
+ end
48
+
49
+ def pull_request_check_runs(repo_full_name, sha)
50
+ client.check_runs_for_ref(repo_full_name, sha).check_runs
51
+ rescue Octokit::Error, Faraday::Error => e
52
+ Rails.logger.warn("GitHub check runs fetch failed: #{e.class}")
53
+ []
54
+ end
55
+
56
+ def pull_request_commit_statuses(repo_full_name, sha)
57
+ client.paginate("repos/#{repo_full_name}/commits/#{sha}/status") do |data, response|
58
+ data.statuses.concat(response.data.statuses)
59
+ end.statuses
60
+ rescue Octokit::Error, Faraday::Error => e
61
+ Rails.logger.warn("GitHub commit statuses fetch failed: #{e.class}")
62
+ []
63
+ end
64
+
41
65
  def pull_request_commit_messages(repo_full_name, number)
42
66
  client
43
67
  .pull_request_commits(repo_full_name, number)
@@ -71,6 +95,19 @@ module CollavreGithub
71
95
  []
72
96
  end
73
97
 
98
+ # The same listing, with the failure reported instead of swallowed. A
99
+ # caller asking whether a specific hook still exists cannot use the form
100
+ # above: an empty array would mean "GitHub says it is gone" and "GitHub did
101
+ # not answer" alike, and those two demand opposite actions.
102
+ def repository_hooks!(repo_full_name)
103
+ client.hooks(repo_full_name)
104
+ end
105
+
106
+ def repository_identity(repo_full_name)
107
+ repository = client.repository(repo_full_name)
108
+ RepositoryIdentity.new(id: repository.id, full_name: repository.full_name)
109
+ end
110
+
74
111
  def create_repository_webhook(repo_full_name, url:, secret:, events:, content_type: "json")
75
112
  client.create_hook(
76
113
  repo_full_name,
@@ -0,0 +1,56 @@
1
+ module CollavreGithub
2
+ module MarkdownSync
3
+ # A synced markdown file is two creatives: the file creative (filename,
4
+ # path anchor) and a single child content creative holding the file body
5
+ # as markdown_source. Both are github_markdown sources, so the body stays
6
+ # read-only until reverse sync lands.
7
+ module ContentCreative
8
+ ROLE = "content".freeze
9
+
10
+ module_function
11
+
12
+ def content?(creative)
13
+ creative.data.is_a?(Hash) && creative.data.dig("source", "role") == ROLE
14
+ end
15
+
16
+ def find(file_creative)
17
+ file_creative.children.where(archived_at: nil).detect { |child| content?(child) }
18
+ end
19
+
20
+ # Creates or updates the content creative under file_creative.
21
+ # Returns the creative when it was newly created, nil otherwise.
22
+ def upsert!(file_creative, markdown, user:)
23
+ existing = find(file_creative)
24
+ if existing
25
+ update!(existing, markdown)
26
+ return nil
27
+ end
28
+
29
+ creative = Collavre::Creative.new(
30
+ parent: file_creative,
31
+ user: user,
32
+ data: { "source" => source_for(file_creative) }
33
+ )
34
+ assign_markdown(creative, markdown)
35
+ creative.save!
36
+ creative
37
+ end
38
+
39
+ def update!(creative, markdown)
40
+ assign_markdown(creative, markdown)
41
+ creative.skip_read_only_source_validation = true
42
+ creative.save!
43
+ end
44
+
45
+ def source_for(file_creative)
46
+ file_creative.data["source"].slice("type", "repo", "path", "repository_link_id").merge("role" => ROLE)
47
+ end
48
+
49
+ def assign_markdown(creative, markdown)
50
+ creative.content_type_input = "markdown"
51
+ creative.markdown_editor = "source"
52
+ creative.markdown_source = markdown
53
+ end
54
+ end
55
+ end
56
+ end
@@ -38,7 +38,10 @@ module CollavreGithub
38
38
 
39
39
  def process_image(match, alt, url, dir, blobs)
40
40
  url_path = strip_fragment_and_query(url)
41
+ return match if url_path.include?("\0")
42
+
41
43
  resolved = resolve_path(dir, url_path)
44
+ return match unless repository_image_path?(resolved)
42
45
 
43
46
  blob = download_and_upload(resolved)
44
47
  return match unless blob
@@ -48,6 +51,18 @@ module CollavreGithub
48
51
  "![#{alt}](#{blob_url})"
49
52
  end
50
53
 
54
+ def repository_image_path?(path)
55
+ return false if path.empty?
56
+
57
+ # Check the URL-decoded form as well because Octokit interpolates the path into a URL.
58
+ decoded = URI::DEFAULT_PARSER.unescape(path).b.tr("\\", "/")
59
+ return false if decoded.include?("\0")
60
+
61
+ [ path, Pathname.new(decoded).cleanpath.to_s ].none? do |candidate|
62
+ candidate.match?(%r{\A(?:/|\.\.?(?:/|\z))})
63
+ end
64
+ end
65
+
51
66
  def process_link(match, label, url, dir)
52
67
  url_path, fragment = url.split("#", 2)
53
68
  url_path = strip_query(url_path)
@@ -102,7 +117,7 @@ module CollavreGithub
102
117
  end
103
118
 
104
119
  def strip_fragment_and_query(url)
105
- url.split("#").first.split("?").first
120
+ url.partition("#").first.partition("?").first
106
121
  end
107
122
 
108
123
  def strip_query(url)
@@ -76,8 +76,9 @@ module CollavreGithub
76
76
  creative.skip_read_only_source_validation = true
77
77
  creative.update!(data: creative.data.merge("source" => source))
78
78
 
79
- processed, blobs = processor.process(content, path)
80
- update_content_comment(creative, processed, blobs)
79
+ processed, _blobs = processor.process(content, path)
80
+ content_creative = ContentCreative.upsert!(creative, processed, user: @user)
81
+ created << content_creative if content_creative
81
82
  end
82
83
 
83
84
  added_paths.each do |path|
@@ -111,10 +112,9 @@ module CollavreGithub
111
112
  creative.save!
112
113
  @synced_creatives[path] = creative
113
114
 
114
- processed, blobs = processor.process(content, path)
115
- comment = create_content_comment(creative, processed)
116
- attach_blobs(comment, blobs) if blobs.any?
115
+ processed, _blobs = processor.process(content, path)
117
116
  created << creative
117
+ created << ContentCreative.upsert!(creative, processed, user: @user)
118
118
  end
119
119
 
120
120
  resequence_affected_parents(created)
@@ -143,36 +143,11 @@ module CollavreGithub
143
143
  .where(archived_at: nil)
144
144
  .where("CAST(data -> 'source' ->> 'repository_link_id' AS INTEGER) = ?", @link.id)
145
145
 
146
- scope.each_with_object({}) { |c, h| h[c.data.dig("source", "path")] = c }
147
- end
148
-
149
- def create_content_comment(creative, markdown_content)
150
- topic = creative.content_topic(fallback_user: @user)
151
- creative.comments.create!(
152
- content: markdown_content,
153
- topic: topic,
154
- user: @user,
155
- skip_dispatch: true
156
- )
157
- end
158
-
159
- def update_content_comment(creative, markdown_content, blobs = [])
160
- topic = creative.content_topic(fallback_user: @user)
161
- comment = creative.comments.where(topic: topic).order(:created_at).first
162
- if comment
163
- comment.images.purge if comment.images.attached?
164
- comment.update!(content: markdown_content)
165
- attach_blobs(comment, blobs) if blobs.any?
166
- else
167
- comment = create_content_comment(creative, markdown_content)
168
- attach_blobs(comment, blobs) if blobs.any?
146
+ scope.each_with_object({}) do |c, h|
147
+ h[c.data.dig("source", "path")] = c unless ContentCreative.content?(c)
169
148
  end
170
149
  end
171
150
 
172
- def attach_blobs(comment, blobs)
173
- blobs.each { |blob| comment.images.attach(blob) }
174
- end
175
-
176
151
  def resequence_affected_parents(new_creatives)
177
152
  parent_ids = new_creatives.map(&:parent_id).compact.uniq
178
153
  Collavre::Creative.transaction do
@@ -184,8 +159,11 @@ module CollavreGithub
184
159
  is_dir = path.end_with?("/") || path == ""
185
160
  [ is_dir ? 0 : 1, c.description.to_s.downcase ]
186
161
  end
187
- sorted.each_with_index do |c, idx|
188
- c.update_column(:sequence, idx) if c.sequence != idx
162
+ changes = sorted.each_with_index.filter_map do |creative, index|
163
+ [ creative, index ] if creative.sequence != index
164
+ end
165
+ Collavre::Creatives::History.record_bulk(changes.map(&:first), operation: "reorder") do
166
+ changes.each { |creative, index| creative.update_column(:sequence, index) }
189
167
  end
190
168
  end
191
169
  end
@@ -77,9 +77,8 @@ module CollavreGithub
77
77
  raw_md = creative.data.dig("source", "markdown")
78
78
  next if raw_md.blank?
79
79
 
80
- processed, blobs = processor.process(raw_md, creative.data.dig("source", "path"))
81
- comment = create_content_comment(creative, processed)
82
- attach_blobs(comment, blobs) if blobs.any?
80
+ processed, _blobs = processor.process(raw_md, creative.data.dig("source", "path"))
81
+ created << ContentCreative.upsert!(creative, processed, user: @user)
83
82
  end
84
83
 
85
84
  resequence_directories_first(created)
@@ -126,20 +125,6 @@ module CollavreGithub
126
125
  end
127
126
  end
128
127
 
129
- def create_content_comment(creative, markdown_content)
130
- topic = creative.content_topic(fallback_user: @user)
131
- creative.comments.create!(
132
- content: markdown_content,
133
- topic: topic,
134
- user: @user,
135
- skip_dispatch: true
136
- )
137
- end
138
-
139
- def attach_blobs(comment, blobs)
140
- blobs.each { |blob| comment.images.attach(blob) }
141
- end
142
-
143
128
  def resequence_directories_first(creatives)
144
129
  Collavre::Creative.transaction do
145
130
  creatives.group_by(&:parent_id).each do |_parent_id, siblings|
@@ -148,8 +133,10 @@ module CollavreGithub
148
133
  is_dir = path.end_with?("/") || path == ""
149
134
  [ is_dir ? 0 : 1, c.description.to_s.downcase ]
150
135
  end
151
- sorted.each_with_index do |c, idx|
152
- c.update_column(:sequence, idx)
136
+ Collavre::Creatives::History.record_bulk(sorted, operation: "reorder") do
137
+ sorted.each_with_index do |creative, index|
138
+ creative.update_column(:sequence, index)
139
+ end
153
140
  end
154
141
  end
155
142
  end
@@ -0,0 +1,93 @@
1
+ module CollavreGithub
2
+ class PrBlockerMonitor
3
+ FAILURE_CONCLUSIONS = %w[failure timed_out startup_failure action_required].freeze
4
+ FAILURE_STATES = %w[error failure].freeze
5
+
6
+ def initialize(channel)
7
+ @channel = channel
8
+ end
9
+
10
+ def call
11
+ repo = channel.repo_full_name
12
+ number = channel.pr_number
13
+ link = repository_link(repo)
14
+ return unless link
15
+
16
+ client = Client.new(link.github_account)
17
+ pr = client.pull_request_details(repo, number)
18
+ return unless pr&.state == "open" && pr.base.repo.id.to_s == link.repository_id.to_s
19
+
20
+ head = pr.head.sha
21
+ return if head.blank?
22
+
23
+ poll_updates(client, link, pr, repo, number)
24
+ end
25
+
26
+ private
27
+
28
+ attr_reader :channel
29
+
30
+ def poll_updates(client, link, pr, repo, number)
31
+ since = channel.discussion_poll_since
32
+ discussion = PrDiscussionEvent.poll(client, repo, number, since: since)
33
+ failures = check_failures(client, repo, pr.head.sha)
34
+ channel.with_lock do
35
+ next unless monitoring?(repo, number)
36
+ next unless repository_link(repo)&.repository_id == link.repository_id
37
+
38
+ channel.start_discussion_tracking!(since)
39
+ record_blockers(pr.head.sha, pr.mergeable, failures)
40
+ discussion.each do |_timestamp, event, payload|
41
+ channel.deliver_event!(event: event, payload: payload)
42
+ end
43
+ end
44
+ end
45
+
46
+ def monitoring?(repo, number)
47
+ channel.active? && !channel.dismissed? && channel.pr_state == "open" &&
48
+ channel.repo_full_name == repo && channel.pr_number == number
49
+ end
50
+
51
+ def repository_link(repo)
52
+ creative = channel.topic.reload.creative
53
+ links = RepositoryLink.where(creative_id: [ creative.id ] + creative.ancestors.pluck(:id))
54
+ .where("LOWER(repository_full_name) = ?", repo.to_s.downcase)
55
+ .includes(:github_account).to_a
56
+ repo_ids = links.map(&:repository_id).uniq
57
+ links.first if repo_ids.one? && repo_ids.first.present?
58
+ end
59
+
60
+ def check_failures(client, repo, head)
61
+ runs = client.pull_request_check_runs(repo, head).filter_map do |run|
62
+ next unless run.status == "completed" && FAILURE_CONCLUSIONS.include?(run.conclusion)
63
+
64
+ [ "run:#{run.id}:#{run.completed_at}", run.name ]
65
+ end
66
+ statuses = client.pull_request_commit_statuses(repo, head).filter_map do |status|
67
+ next unless FAILURE_STATES.include?(status.state)
68
+
69
+ [ "status:#{status.id}", status.context ]
70
+ end
71
+ (runs + statuses).to_h
72
+ end
73
+
74
+ def record_blockers(head, mergeable, failures)
75
+ previous = channel.config.fetch("pr_blockers", {})
76
+ notified = previous["head"] == head ? previous.fetch("check_ids", []) : []
77
+ new_failures = failures.except(*notified)
78
+ conflict = mergeable.nil? ? previous["conflict"] : !mergeable
79
+
80
+ if conflict && !previous["conflict"]
81
+ channel.inject_into_topic!(channel.blocker_message("merge_conflict_message"))
82
+ end
83
+ if new_failures.any?
84
+ channel.inject_into_topic!(
85
+ channel.blocker_message("failed_checks_message", checks: new_failures.values.map(&:squish).uniq.join(", "))
86
+ )
87
+ end
88
+
89
+ current = { "head" => head, "conflict" => conflict, "check_ids" => notified | failures.keys }
90
+ channel.update!(config: channel.config.merge("pr_blockers" => current)) if current != previous
91
+ end
92
+ end
93
+ end