Repository navigation
feat: poll lore for mailing-list updates #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
kairosci
wants to merge
7
commits into
gitgitgadget:main
Choose a base branch
from
kairosci:codex/low-latency-mail-mirroring
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+377
−14
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
9cb7661
feat: compare mailing-list mirror refs
kairosci 9ab3e22
feat: poll lore for mailing-list updates
kairosci d09c3a0
docs: explain low-latency mirror polling
kairosci 1434822
fix: validate mailing-list mirror refs
kairosci 406183d
test: cover mailing-list mirror polling
kairosci 8a9d859
refactor: reuse shared HTTPS helper for mirror refs
kairosci 0972b32
fix: throttle mailing-list mirror polling
kairosci File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| const { httpsRequestBuffer } = require('./https-request') | ||
|
|
||
| const packetLine = value => { | ||
| const data = Buffer.from(value) | ||
| const length = data.length + 4 | ||
| if (length > 0xffff) throw new Error('Git protocol packet is too large') | ||
| return Buffer.concat([Buffer.from(length.toString(16).padStart(4, '0')), data]) | ||
| } | ||
|
|
||
| const parsePacketLines = body => { | ||
| const packets = [] | ||
| let offset = 0 | ||
| while (offset < body.length) { | ||
| if (offset + 4 > body.length) throw new Error('Truncated Git protocol packet header') | ||
| const header = body.toString('ascii', offset, offset + 4) | ||
| if (!/^[0-9a-f]{4}$/i.test(header)) throw new Error(`Invalid Git protocol packet header: ${header}`) | ||
|
|
||
| const length = Number.parseInt(header, 16) | ||
| offset += 4 | ||
| if (length === 0 || length === 1 || length === 2) { | ||
| packets.push({ length }) | ||
| continue | ||
| } | ||
| // The pkt-line length includes its four-byte header. | ||
| const payloadLength = length - 4 | ||
| if (payloadLength < 0 || offset + payloadLength > body.length) { | ||
| throw new Error(`Invalid Git protocol packet length: ${length}`) | ||
| } | ||
| packets.push({ data: body.subarray(offset, offset + payloadLength) }) | ||
| offset += payloadLength | ||
| } | ||
| return packets | ||
| } | ||
|
|
||
| const parseCapabilities = (body, url) => { | ||
| const packets = parsePacketLines(body) | ||
| let index = 0 | ||
|
|
||
| // GitHub includes the HTTP service announcement; lore starts at version 2. | ||
| if (packets[index]?.data?.toString('utf8').trimEnd() === '# service=git-upload-pack') { | ||
| index++ | ||
| if (packets[index]?.length !== 0) throw new Error(`Invalid service announcement from ${url}`) | ||
| index++ | ||
| } | ||
| if (packets[index]?.data?.toString('utf8').trimEnd() !== 'version 2') { | ||
| throw new Error(`Git server at ${url} did not advertise protocol v2`) | ||
| } | ||
|
|
||
| const capabilities = new Set() | ||
| for (index++; index < packets.length && packets[index].length !== 0; index++) { | ||
| const capability = packets[index].data?.toString('utf8').trimEnd() | ||
| if (capability) capabilities.add(capability.split('=', 1)[0]) | ||
| } | ||
| if (!capabilities.has('ls-refs')) throw new Error(`Git server at ${url} does not support ls-refs`) | ||
| } | ||
|
|
||
| const parseRefAdvertisement = (body, ref, url) => { | ||
| for (const packet of parsePacketLines(body)) { | ||
| const line = packet.data?.toString('utf8').trimEnd() | ||
| if (!line) continue | ||
| const match = line.match(/^([0-9a-f]{40,64}) (\S+)$/i) | ||
| if (match && match[2] === ref) return match[1] | ||
| } | ||
| throw new Error(`Could not find ${ref} in ${url}`) | ||
| } | ||
|
|
||
| const getRef = async (context, url, ref) => { | ||
| const { hostname, pathname } = new URL(url) | ||
| const basePath = pathname.replace(/\/+$/, '') | ||
| const protocolHeaders = { | ||
| 'Git-Protocol': 'version=2', | ||
| 'User-Agent': 'GitGitGadget/1.0' | ||
| } | ||
| const advertisement = await httpsRequestBuffer( | ||
| context, | ||
| hostname, | ||
| 'GET', | ||
| `${basePath}/info/refs?service=git-upload-pack`, | ||
| undefined, | ||
| { ...protocolHeaders, Accept: 'application/x-git-upload-pack-advertisement' } | ||
| ) | ||
| parseCapabilities(advertisement, url) | ||
|
|
||
| const request = Buffer.concat([ | ||
| packetLine('command=ls-refs\n'), | ||
| Buffer.from('0001'), | ||
| packetLine(`ref-prefix ${ref}\n`), | ||
| Buffer.from('0000') | ||
| ]) | ||
| const response = await httpsRequestBuffer( | ||
| context, | ||
| hostname, | ||
| 'POST', | ||
| `${basePath}/git-upload-pack`, | ||
| request, | ||
| { | ||
| ...protocolHeaders, | ||
| Accept: 'application/x-git-upload-pack-result', | ||
| 'Content-Type': 'application/x-git-upload-pack-request' | ||
| } | ||
| ) | ||
| return parseRefAdvertisement(response, ref, url) | ||
| } | ||
|
|
||
| const isUpToDate = async (config, context) => { | ||
| if (!config.mailrepo.mirrorURL) return true | ||
|
|
||
| const epoch = config.mailrepo.public_inbox_epoch || 1 | ||
| const sourceURL = new URL(config.mailrepo.url) | ||
| sourceURL.pathname = `${sourceURL.pathname.replace(/\/+$/, '')}/${epoch}` | ||
| sourceURL.search = '' | ||
| sourceURL.hash = '' | ||
| const mirrorURL = new URL(config.mailrepo.mirrorURL) | ||
| if (sourceURL.protocol !== 'https:' || mirrorURL.protocol !== 'https:') { | ||
| throw new Error('Mailing-list source and mirror URLs must use HTTPS') | ||
| } | ||
| mirrorURL.pathname = mirrorURL.pathname.replace(/\/+$/, '') | ||
| if (!mirrorURL.pathname.endsWith('.git')) mirrorURL.pathname += '.git' | ||
|
|
||
| const [sourceOID, mirrorOID] = await Promise.all([ | ||
| getRef(context, sourceURL.href, `refs/heads/${config.mailrepo.branch}`), | ||
| getRef(context, mirrorURL.href, config.mailrepo.mirrorRef || `refs/heads/lore-${epoch}`) | ||
| ]) | ||
| return sourceOID === mirrorOID | ||
| } | ||
|
|
||
| module.exports = { isUpToDate, parseCapabilities, parsePacketLines, parseRefAdvertisement } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| const { isUpToDate } = require('./mailing-list-mirror') | ||
|
|
||
| const SYNC_WORKFLOW = 'sync-mailing-list-mirror.yml' | ||
| const WORKFLOWS_BRANCH = 'main' | ||
| const SYNC_INTERVAL_MS = 5 * 60 * 1000 | ||
|
|
||
| const syncMailingListMirror = async context => { | ||
| try { | ||
| const { readFileSync } = require('fs') | ||
| const config = JSON.parse(readFileSync(`${__dirname}/gitgitgadget-config.json`)) | ||
| if (await isUpToDate(config, context)) { | ||
| context.log('Mailing-list mirror is up to date') | ||
| return | ||
| } | ||
|
|
||
| const { owner, name } = config.workflowsRepo | ||
| const { getInstallationIdForRepo } = require('./get-installation-id-for-repo') | ||
| const { getInstallationAccessToken } = require('./get-installation-access-token') | ||
| const installationID = await getInstallationIdForRepo(context, owner, name) | ||
| const token = await getInstallationAccessToken(context, installationID) | ||
|
kairosci marked this conversation as resolved.
Resolved
|
||
| const { listWorkflowRuns, triggerWorkflowDispatch } = require('./trigger-workflow-dispatch') | ||
|
|
||
| const runs = await listWorkflowRuns(context, token, owner, name, SYNC_WORKFLOW, WORKFLOWS_BRANCH) | ||
| if (runs.some(run => run.status === 'queued' || run.status === 'in_progress')) { | ||
| context.log('Skipping mirror sync; a run is already queued or in progress') | ||
| return | ||
| } | ||
| const completedRecently = runs.some(run => { | ||
| const completedAt = Date.parse(run.updated_at) | ||
| return run.status === 'completed' && Number.isFinite(completedAt) && Date.now() - completedAt < SYNC_INTERVAL_MS | ||
| }) | ||
| if (completedRecently) { | ||
| context.log('Skipping mirror sync; a run completed within the last five minutes') | ||
| return | ||
| } | ||
|
|
||
| const run = await triggerWorkflowDispatch(context, token, owner, name, SYNC_WORKFLOW, WORKFLOWS_BRANCH) | ||
| context.log(`Triggered mailing-list mirror sync: ${run.html_url}`) | ||
| } catch (e) { | ||
| context.log('Caught exception ', e) | ||
| throw e | ||
| } | ||
| } | ||
|
|
||
| module.exports = syncMailingListMirror | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| const mockRequest = jest.fn() | ||
| jest.mock('https', () => ({ request: mockRequest })) | ||
|
|
||
| const { EventEmitter } = require('events') | ||
| const { httpsRequestBuffer } = require('../GitGitGadget/https-request') | ||
|
|
||
| test('sends and receives Git protocol data as buffers with a timeout', async () => { | ||
| const request = new EventEmitter() | ||
| request.write = jest.fn() | ||
| request.setTimeout = jest.fn() | ||
| request.destroy = jest.fn() | ||
| request.end = () => { | ||
| const response = new EventEmitter() | ||
| response.statusCode = 200 | ||
| mockRequest.mock.calls[0][1](response) | ||
| response.emit('data', Buffer.from([0, 1, 2, 255])) | ||
| response.emit('end') | ||
| } | ||
| mockRequest.mockReturnValue(request) | ||
|
|
||
| const body = Buffer.from([0, 1, 2]) | ||
| const headers = { | ||
| Accept: 'application/x-git-upload-pack-result', | ||
| 'Content-Type': 'application/x-git-upload-pack-request' | ||
| } | ||
| const response = await httpsRequestBuffer(null, 'example.com', 'POST', '/git-upload-pack', body, headers) | ||
|
|
||
| expect(response).toEqual(Buffer.from([0, 1, 2, 255])) | ||
| expect(mockRequest.mock.calls[0][0].headers).toMatchObject({ | ||
| ...headers, | ||
| 'Content-Length': body.length | ||
| }) | ||
| expect(request.write).toHaveBeenCalledWith(body) | ||
| expect(request.setTimeout).toHaveBeenCalledWith(30_000, expect.any(Function)) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| const mockHttpsRequestBuffer = jest.fn() | ||
| jest.mock('../GitGitGadget/https-request', () => ({ httpsRequestBuffer: mockHttpsRequestBuffer })) | ||
|
|
||
| const { isUpToDate, parseRefAdvertisement } = require('../GitGitGadget/mailing-list-mirror') | ||
|
|
||
| const packet = line => { | ||
| const data = Buffer.from(line) | ||
| return Buffer.concat([Buffer.from((data.length + 4).toString(16).padStart(4, '0')), data]) | ||
| } | ||
| const capabilities = serviceAnnouncement => Buffer.concat([ | ||
| ...(serviceAnnouncement ? [packet('# service=git-upload-pack\n'), Buffer.from('0000')] : []), | ||
| packet('version 2\n'), | ||
| packet('ls-refs=unborn\n'), | ||
| Buffer.from('0000') | ||
| ]) | ||
|
|
||
| const config = () => ({ | ||
| mailrepo: { | ||
| url: 'https://lore.kernel.org/git', | ||
| branch: 'master', | ||
| public_inbox_epoch: 1, | ||
| mirrorURL: 'https://github.com/gitgitgadget/git-mailing-list-mirror/', | ||
| mirrorRef: 'refs/heads/lore-1' | ||
| } | ||
| }) | ||
|
|
||
| beforeEach(() => jest.clearAllMocks()) | ||
|
|
||
| test('requests only the configured refs from both protocol-v2 servers', async () => { | ||
| const oid = 'a'.repeat(40) | ||
| mockHttpsRequestBuffer.mockImplementation(async (_context, hostname, method) => { | ||
| if (method === 'GET') return capabilities(hostname === 'github.com') | ||
| return packet(`${oid} ${hostname === 'github.com' ? 'refs/heads/lore-1' : 'refs/heads/master'}\n`) | ||
| }) | ||
|
|
||
| await expect(isUpToDate(config())).resolves.toBe(true) | ||
|
|
||
| const requests = mockHttpsRequestBuffer.mock.calls | ||
| expect(requests.filter(([, , method]) => method === 'POST')).toHaveLength(2) | ||
| expect(requests.filter(([, , method]) => method === 'POST').every(([, , , , body]) => | ||
| body.toString().includes('ref-prefix refs/heads/'))).toBe(true) | ||
| expect(requests.some(([, hostname, , path]) => hostname === 'github.com' && path.includes('.git/git-upload-pack'))).toBe(true) | ||
| }) | ||
|
|
||
| test('matches the complete ref name, not a longer ref with the same prefix', () => { | ||
| const wanted = 'a'.repeat(40) | ||
| const other = 'b'.repeat(40) | ||
| const body = Buffer.concat([ | ||
| packet(`${other} refs/heads/lore-10\n`), | ||
| packet(`${wanted} refs/heads/lore-1\n`), | ||
| Buffer.from('0000') | ||
| ]) | ||
|
|
||
| expect(parseRefAdvertisement(body, 'refs/heads/lore-1', 'https://example.com/repo.git')).toBe(wanted) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.