From 9cb7661e8315dde345457572126a46b953b3db1a Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Sat, 28 Nov 2026 12:37:36 +0100 Subject: [PATCH 1/7] feat: compare mailing-list mirror refs The mirror workflow needs to know whether lore has published a newer tip before it can be triggered on demand. Compare the refs advertised by lore.kernel.org and the configured GitHub mirror so a caller can make that decision without fetching the mail archive. --- GitGitGadget/mailing-list-mirror.js | 65 +++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 GitGitGadget/mailing-list-mirror.js diff --git a/GitGitGadget/mailing-list-mirror.js b/GitGitGadget/mailing-list-mirror.js new file mode 100644 index 0000000..4f82b50 --- /dev/null +++ b/GitGitGadget/mailing-list-mirror.js @@ -0,0 +1,65 @@ +const https = require('https') + +const getRef = async (url, ref) => { + const { hostname, pathname } = new URL(url) + const requestPath = `${pathname.replace(/\/$/, '')}/info/refs?service=git-upload-pack` + const body = await new Promise((resolve, reject) => { + const request = https.request({ + hostname, + method: 'GET', + path: requestPath, + headers: { + 'Git-Protocol': 'version=1', + 'User-Agent': 'GitGitGadget/1.0' + } + }, response => { + const chunks = [] + response.on('data', chunk => chunks.push(chunk)) + response.on('error', reject) + response.on('end', () => { + if (response.statusCode !== 200) { + reject(new Error(`Could not read ${url}: HTTP ${response.statusCode}`)) + return + } + resolve(Buffer.concat(chunks).toString('utf8')) + }) + }) + request.on('error', reject) + request.setTimeout(30_000, () => request.destroy(new Error(`Timed out reading ${url}`))) + request.end() + }) + + let offset = 0 + while (offset + 4 <= body.length) { + const length = Number.parseInt(body.slice(offset, offset + 4), 16) + if (length === 0) { + offset += 4 + continue + } + if (!Number.isInteger(length) || length < 4 || offset + length > body.length) break + + const line = body.slice(offset + 4, offset + length).split('\0', 1)[0].trim() + const match = line.match(/^([0-9a-f]{40,64})\s+(.+)$/) + if (match && match[2] === ref) return match[1] + offset += length + } + + throw new Error(`Could not find ${ref} in ${url}`) +} + +const isUpToDate = async config => { + if (!config.mailrepo.mirrorURL) return true + + const epoch = config.mailrepo.public_inbox_epoch || 1 + const sourceURL = new URL(`${epoch}/`, config.mailrepo.url).href + const mirrorURL = new URL(config.mailrepo.mirrorURL) + if (!mirrorURL.pathname.endsWith('.git')) mirrorURL.pathname += '.git' + + const [sourceOID, mirrorOID] = await Promise.all([ + getRef(sourceURL, `refs/heads/${config.mailrepo.branch}`), + getRef(mirrorURL.href, config.mailrepo.mirrorRef || `refs/heads/lore-${epoch}`) + ]) + return sourceOID === mirrorOID +} + +module.exports = { isUpToDate } From 9ab3e2253c2023c203a73f8897f0d1e241f4042b Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Sat, 28 Nov 2026 12:37:46 +0100 Subject: [PATCH 2/7] feat: poll lore for mailing-list updates The GitHub Actions mirror schedule is best-effort and can start much later than its five-minute interval. Check lore and the GitHub mirror once a minute, and dispatch the existing sync workflow only when their refs differ. Skip a dispatch while a sync is queued or running so repeated timer ticks do not create redundant work. --- GitGitGadget/sync-mailing-list-mirror.js | 34 ++++++++++++++++++++++++ sync-mailing-list-mirror/function.json | 10 +++++++ sync-mailing-list-mirror/index.js | 3 +++ 3 files changed, 47 insertions(+) create mode 100644 GitGitGadget/sync-mailing-list-mirror.js create mode 100644 sync-mailing-list-mirror/function.json create mode 100644 sync-mailing-list-mirror/index.js diff --git a/GitGitGadget/sync-mailing-list-mirror.js b/GitGitGadget/sync-mailing-list-mirror.js new file mode 100644 index 0000000..43d0bcd --- /dev/null +++ b/GitGitGadget/sync-mailing-list-mirror.js @@ -0,0 +1,34 @@ +const { isUpToDate } = require('./mailing-list-mirror') + +module.exports = async context => { + try { + const { readFileSync } = require('fs') + const config = JSON.parse(readFileSync(`${__dirname}/gitgitgadget-config.json`)) + if (await isUpToDate(config)) { + context.log('Mailing-list mirror is up to date') + return + } + + const { owner, name } = config.workflowsRepo + const workflow = 'sync-mailing-list-mirror.yml' + 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) + const { listWorkflowRuns, triggerWorkflowDispatch } = require('./trigger-workflow-dispatch') + + for (const status of ['queued', 'in_progress']) { + const runs = await listWorkflowRuns(context, token, owner, name, workflow, 'main', status) + if (runs.length) { + context.log(`Skipping mirror sync; a run is already ${status}`) + return + } + } + + const run = await triggerWorkflowDispatch(context, token, owner, name, workflow, 'main') + context.log(`Triggered mailing-list mirror sync: ${run.html_url}`) + } catch (e) { + context.log('Caught exception ', e) + throw e + } +} diff --git a/sync-mailing-list-mirror/function.json b/sync-mailing-list-mirror/function.json new file mode 100644 index 0000000..d257407 --- /dev/null +++ b/sync-mailing-list-mirror/function.json @@ -0,0 +1,10 @@ +{ + "bindings": [ + { + "name": "timer", + "type": "timerTrigger", + "direction": "in", + "schedule": "0 */1 * * * *" + } + ] +} diff --git a/sync-mailing-list-mirror/index.js b/sync-mailing-list-mirror/index.js new file mode 100644 index 0000000..635dced --- /dev/null +++ b/sync-mailing-list-mirror/index.js @@ -0,0 +1,3 @@ +const syncMailingListMirror = require('../GitGitGadget/sync-mailing-list-mirror') + +module.exports = async context => syncMailingListMirror(context) From d09c3a0ed583fd72b45fa5786c56c68c8dcbae14 Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Sat, 28 Nov 2026 12:37:46 +0100 Subject: [PATCH 3/7] docs: explain low-latency mirror polling Describe the timer, its one-minute polling interval, and the existing scheduled fallback so operators know how mirror updates are triggered and what still affects delivery time. --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index e4f54a8..7af7662 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,12 @@ Finally, [run the Function locally](https://learn.microsoft.com/en-us/azure/azur You can also run/debug it via VS Code, there is a default configuration called "Attach to Node Functions". +### Keeping the mailing-list mirror current + +The `sync-mailing-list-mirror` timer checks lore.kernel.org and the GitHub mirror once a minute. It dispatches the existing mirror workflow only when their advertised refs differ and skips the dispatch while another mirror run is queued or running. The workflow's five-minute schedule remains as a fallback. + +The timer uses the existing `AzureWebJobsStorage` setting for its schedule and lock. Delivery time still depends on lore.kernel.org publishing the message and Azure running the timer. + ## How to set up this GitHub App This process looks a bit complex, the main reason for that being that three things have to be set up essentially simultaneously: an Azure Function, a GitHub repository and a GitHub App. From 1434822864228716135d42d6af140054070e8770 Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Sat, 28 Nov 2026 12:52:24 +0100 Subject: [PATCH 4/7] fix: validate mailing-list mirror refs The source and mirror may be configured with or without trailing slashes, and neither ref should be read over an unencrypted connection. Normalize their URLs before requesting the Git protocol advertisement, and isolate its packet-line parser so malformed or missing refs fail clearly. --- GitGitGadget/mailing-list-mirror.js | 52 ++++++++++++++++++----------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/GitGitGadget/mailing-list-mirror.js b/GitGitGadget/mailing-list-mirror.js index 4f82b50..047471d 100644 --- a/GitGitGadget/mailing-list-mirror.js +++ b/GitGitGadget/mailing-list-mirror.js @@ -1,5 +1,27 @@ const https = require('https') +const parseRefAdvertisement = (body, ref, url) => { + let offset = 0 + while (offset + 4 <= body.length) { + const packetHeader = body.slice(offset, offset + 4) + if (!/^[0-9a-f]{4}$/i.test(packetHeader)) break + + const length = Number.parseInt(packetHeader, 16) + if (length === 0 || length === 1 || length === 2) { + offset += 4 + continue + } + if (length < 4 || offset + length > body.length) break + + const line = body.slice(offset + 4, offset + length).split('\0', 1)[0].trim() + const match = line.match(/^([0-9a-f]{40,64})\s+(.+)$/) + if (match && match[2] === ref) return match[1] + offset += length + } + + throw new Error(`Could not find ${ref} in ${url}`) +} + const getRef = async (url, ref) => { const { hostname, pathname } = new URL(url) const requestPath = `${pathname.replace(/\/$/, '')}/info/refs?service=git-upload-pack` @@ -29,37 +51,29 @@ const getRef = async (url, ref) => { request.end() }) - let offset = 0 - while (offset + 4 <= body.length) { - const length = Number.parseInt(body.slice(offset, offset + 4), 16) - if (length === 0) { - offset += 4 - continue - } - if (!Number.isInteger(length) || length < 4 || offset + length > body.length) break - - const line = body.slice(offset + 4, offset + length).split('\0', 1)[0].trim() - const match = line.match(/^([0-9a-f]{40,64})\s+(.+)$/) - if (match && match[2] === ref) return match[1] - offset += length - } - - throw new Error(`Could not find ${ref} in ${url}`) + return parseRefAdvertisement(body, ref, url) } const isUpToDate = async config => { if (!config.mailrepo.mirrorURL) return true const epoch = config.mailrepo.public_inbox_epoch || 1 - const sourceURL = new URL(`${epoch}/`, config.mailrepo.url).href + 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(sourceURL, `refs/heads/${config.mailrepo.branch}`), + getRef(sourceURL.href, `refs/heads/${config.mailrepo.branch}`), getRef(mirrorURL.href, config.mailrepo.mirrorRef || `refs/heads/lore-${epoch}`) ]) return sourceOID === mirrorOID } -module.exports = { isUpToDate } +module.exports = { isUpToDate, parseRefAdvertisement } From 406183d139f228761350e261b78d41e2a2dfd349 Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Sat, 28 Nov 2026 12:52:24 +0100 Subject: [PATCH 5/7] test: cover mailing-list mirror polling The timer must avoid unnecessary GitHub API calls when the mirror is current and avoid duplicate sync runs while work is pending. Cover ref parsing and comparison, transport failures, and the dispatch decisions so these paths remain reviewable as the polling behavior changes. --- __tests__/mailing-list-mirror.test.js | 125 +++++++++++++++++++++ __tests__/sync-mailing-list-mirror.test.js | 82 ++++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 __tests__/mailing-list-mirror.test.js create mode 100644 __tests__/sync-mailing-list-mirror.test.js diff --git a/__tests__/mailing-list-mirror.test.js b/__tests__/mailing-list-mirror.test.js new file mode 100644 index 0000000..e2162ae --- /dev/null +++ b/__tests__/mailing-list-mirror.test.js @@ -0,0 +1,125 @@ +jest.mock('https') +const https = require('https') +const { isUpToDate, parseRefAdvertisement } = require('../GitGitGadget/mailing-list-mirror') +const EventEmitter = require('events') + +let responses + +https.request = jest.fn((options, callback) => { + const { body, statusCode = 200 } = responses.shift() + const request = new EventEmitter() + request.setTimeout = jest.fn() + request.end = () => { + const response = new EventEmitter() + response.statusCode = statusCode + callback(response) + response.emit('data', Buffer.from(body)) + response.emit('end') + } + return request +}) + +const packet = line => `${(Buffer.byteLength(line) + 4).toString(16).padStart(4, '0')}${line}` + +const advertisement = (refs, capabilities = 'multi_ack side-band') => [ + packet('# service=git-upload-pack\n'), + '0000', + packet('version 1\n'), + ...refs.map(([oid, ref], index) => packet(`${oid} ${ref}${index === 0 ? `\0${capabilities}` : ''}\n`)), + '0000' +].join('') + +const makeConfig = () => ({ + 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() + responses = [] +}) + +test('read a ref from a Git protocol v1 advertisement', () => { + const head = 'a'.repeat(40) + const master = 'b'.repeat(40) + const mirror = 'c'.repeat(40) + const body = advertisement([ + [head, 'HEAD'], + [master, 'refs/heads/master'], + [mirror, 'refs/heads/lore-1'] + ]) + + expect(parseRefAdvertisement(body, 'refs/heads/lore-1', 'https://example.com/repo.git')).toBe(mirror) +}) + +test('reject an advertisement without the requested ref', () => { + const body = advertisement([['a'.repeat(40), 'refs/heads/master']]) + + expect(() => parseRefAdvertisement(body, 'refs/heads/lore-1', 'https://example.com/repo.git')) + .toThrow('Could not find refs/heads/lore-1') +}) + +test('reject a malformed packet advertisement', () => { + expect(() => parseRefAdvertisement('zzzz', 'refs/heads/master', 'https://example.com/repo.git')) + .toThrow('Could not find refs/heads/master') +}) + +test('compare the lore and mirror refs when URLs lack or have trailing slashes', async () => { + const source = 'a'.repeat(40) + responses = [ + { body: advertisement([[source, 'refs/heads/master']]) }, + { body: advertisement([[source, 'refs/heads/lore-1']]) } + ] + + await expect(isUpToDate(makeConfig())).resolves.toBe(true) + + expect(https.request.mock.calls.map(([options]) => [options.hostname, options.path])).toEqual([ + ['lore.kernel.org', '/git/1/info/refs?service=git-upload-pack'], + ['github.com', '/gitgitgadget/git-mailing-list-mirror.git/info/refs?service=git-upload-pack'] + ]) + for (const [options] of https.request.mock.calls) { + expect(options.headers['Git-Protocol']).toBe('version=1') + expect(options.headers['User-Agent']).toBe('GitGitGadget/1.0') + } +}) + +test('report when the GitHub mirror is behind lore', async () => { + responses = [ + { body: advertisement([['a'.repeat(40), 'refs/heads/master']]) }, + { body: advertisement([['b'.repeat(40), 'refs/heads/lore-1']]) } + ] + + await expect(isUpToDate(makeConfig())).resolves.toBe(false) +}) + +test('fail when either ref advertisement cannot be fetched', async () => { + responses = [ + { body: 'Forbidden', statusCode: 403 }, + { body: advertisement([['a'.repeat(40), 'refs/heads/lore-1']]) } + ] + + await expect(isUpToDate(makeConfig())).rejects.toThrow('HTTP 403') +}) + +test('reject non-HTTPS source and mirror URLs', async () => { + const config = makeConfig() + config.mailrepo.mirrorURL = 'http://github.com/gitgitgadget/git-mailing-list-mirror' + + await expect(isUpToDate(config)).rejects.toThrow('must use HTTPS') + + expect(https.request).not.toHaveBeenCalled() +}) + +test('skip ref polling when no GitHub mirror is configured', async () => { + const config = makeConfig() + delete config.mailrepo.mirrorURL + + await expect(isUpToDate(config)).resolves.toBe(true) + + expect(https.request).not.toHaveBeenCalled() +}) diff --git a/__tests__/sync-mailing-list-mirror.test.js b/__tests__/sync-mailing-list-mirror.test.js new file mode 100644 index 0000000..691d74f --- /dev/null +++ b/__tests__/sync-mailing-list-mirror.test.js @@ -0,0 +1,82 @@ +const mockIsUpToDate = jest.fn() +const mockGetInstallationIdForRepo = jest.fn() +const mockGetInstallationAccessToken = jest.fn() +const mockListWorkflowRuns = jest.fn() +const mockTriggerWorkflowDispatch = jest.fn() + +jest.mock('../GitGitGadget/mailing-list-mirror', () => ({ isUpToDate: mockIsUpToDate })) +jest.mock('../GitGitGadget/get-installation-id-for-repo', () => ({ + getInstallationIdForRepo: mockGetInstallationIdForRepo +})) +jest.mock('../GitGitGadget/get-installation-access-token', () => ({ + getInstallationAccessToken: mockGetInstallationAccessToken +})) +jest.mock('../GitGitGadget/trigger-workflow-dispatch', () => ({ + listWorkflowRuns: mockListWorkflowRuns, + triggerWorkflowDispatch: mockTriggerWorkflowDispatch +})) + +const syncMailingListMirror = require('../GitGitGadget/sync-mailing-list-mirror') + +const makeContext = () => ({ log: jest.fn() }) + +beforeEach(() => { + jest.clearAllMocks() + mockIsUpToDate.mockResolvedValue(true) + mockGetInstallationIdForRepo.mockResolvedValue(17) + mockGetInstallationAccessToken.mockResolvedValue('installation-token') + mockListWorkflowRuns.mockResolvedValue([]) + mockTriggerWorkflowDispatch.mockResolvedValue({ html_url: 'https://github.com/run/1' }) +}) + +test('does not dispatch a sync when the mirror is current', async () => { + const context = makeContext() + + await syncMailingListMirror(context) + + expect(mockGetInstallationIdForRepo).not.toHaveBeenCalled() + expect(mockTriggerWorkflowDispatch).not.toHaveBeenCalled() + expect(context.log).toHaveBeenCalledWith('Mailing-list mirror is up to date') +}) + +test('dispatches a sync when lore is ahead and no run is active', async () => { + const context = makeContext() + mockIsUpToDate.mockResolvedValue(false) + + await syncMailingListMirror(context) + + expect(mockListWorkflowRuns).toHaveBeenCalledTimes(2) + expect(mockTriggerWorkflowDispatch).toHaveBeenCalledWith( + context, + 'installation-token', + 'gitgitgadget-workflows', + 'gitgitgadget-workflows', + 'sync-mailing-list-mirror.yml', + 'main' + ) +}) + +test.each(['queued', 'in_progress'])('does not dispatch while a sync is %s', async status => { + const context = makeContext() + mockIsUpToDate.mockResolvedValue(false) + mockListWorkflowRuns.mockImplementation(async (_context, _token, _owner, _repo, _workflow, _branch, queriedStatus) => { + return queriedStatus === status ? [{ status }] : [] + }) + + await syncMailingListMirror(context) + + expect(mockTriggerWorkflowDispatch).not.toHaveBeenCalled() + expect(context.log).toHaveBeenCalledWith(`Skipping mirror sync; a run is already ${status}`) +}) + +test('propagates a failure to read the mailing-list refs', async () => { + const context = makeContext() + const error = new Error('lore is unavailable') + mockIsUpToDate.mockRejectedValue(error) + + await expect(syncMailingListMirror(context)).rejects.toThrow('lore is unavailable') + + expect(mockGetInstallationIdForRepo).not.toHaveBeenCalled() + expect(mockTriggerWorkflowDispatch).not.toHaveBeenCalled() + expect(context.log).toHaveBeenCalledWith('Caught exception ', error) +}) From 8a9d859375b3ba2d6bac01721d1368c982ef13a0 Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Fri, 4 Dec 2026 18:49:02 +0100 Subject: [PATCH 6/7] refactor: reuse shared HTTPS helper for mirror refs --- GitGitGadget/https-request.js | 46 ++++++--- GitGitGadget/mailing-list-mirror.js | 138 +++++++++++++++++-------- __tests__/https-request.test.js | 35 +++++++ __tests__/mailing-list-mirror.test.js | 142 +++++++------------------- 4 files changed, 196 insertions(+), 165 deletions(-) create mode 100644 __tests__/https-request.test.js diff --git a/GitGitGadget/https-request.js b/GitGitGadget/https-request.js index f8094fc..e290c1c 100644 --- a/GitGitGadget/https-request.js +++ b/GitGitGadget/https-request.js @@ -1,15 +1,15 @@ const gently = require('./gently') -const httpsRequest = async (context, hostname, method, requestPath, body, headers) => { +const httpsRequest = async (context, hostname, method, requestPath, body, headers, responseType = 'json', timeout = 0) => { headers = { 'User-Agent': 'GitForWindowsHelper/0.0', Accept: 'application/json', ...headers || {} } - if (body) { - if (typeof body === 'object') body = JSON.stringify(body) - headers['Content-Type'] = 'application/json' - headers['Content-Length'] = body.length + if (body !== undefined && body !== null) { + if (typeof body === 'object' && !Buffer.isBuffer(body)) body = JSON.stringify(body) + headers['Content-Type'] = headers['Content-Type'] || 'application/json' + headers['Content-Length'] = typeof body === 'string' ? Buffer.byteLength(body) : body.length } const options = { port: 443, @@ -24,17 +24,21 @@ const httpsRequest = async (context, hostname, method, requestPath, body, header const req = https.request(options, res => { res.on('error', e => reject(e)) - if (res.statusCode === 204) resolve({ - statusCode: res.statusCode, - statusMessage: res.statusMessage, - headers: res.headers - }) + if (res.statusCode === 204) { + resolve({ + statusCode: res.statusCode, + statusMessage: res.statusMessage, + headers: res.headers + }) + return + } const chunks = [] res.on('data', data => chunks.push(data)) res.on('end', () => { - const json = Buffer.concat(chunks).toString('utf-8') + const response = Buffer.concat(chunks) if (res.statusCode > 299) { + const json = response.toString('utf-8') reject({ statusCode: res.statusCode, statusMessage: res.statusMessage, @@ -45,14 +49,24 @@ const httpsRequest = async (context, hostname, method, requestPath, body, header }) return } + if (responseType === 'buffer') { + resolve(response) + return + } + const text = response.toString('utf-8') + if (responseType === 'text') { + resolve(text) + return + } try { - resolve(JSON.parse(json)) + resolve(JSON.parse(text)) } catch (e) { - reject(`Invalid JSON: ${json}`) + reject(`Invalid JSON: ${text}`) } }) }) req.on('error', err => reject(err)) + if (timeout) req.setTimeout(timeout, () => req.destroy(new Error(`Timed out requesting ${requestPath}`))) if (body) req.write(body) req.end() } catch (e) { @@ -61,6 +75,9 @@ const httpsRequest = async (context, hostname, method, requestPath, body, header }) } +const httpsRequestBuffer = (context, hostname, method, requestPath, body, headers, timeout = 30_000) => + httpsRequest(context, hostname, method, requestPath, body, headers, 'buffer', timeout) + const doesURLReturn404 = async url => { const match = url.match(/^https:\/\/([^/]+?)(:\d+)?(\/.*)?$/) if (!match) throw new Error(`Could not parse URL ${url}`) @@ -84,5 +101,6 @@ const doesURLReturn404 = async url => { module.exports = { httpsRequest, + httpsRequestBuffer, doesURLReturn404 -} \ No newline at end of file +} diff --git a/GitGitGadget/mailing-list-mirror.js b/GitGitGadget/mailing-list-mirror.js index 047471d..e316929 100644 --- a/GitGitGadget/mailing-list-mirror.js +++ b/GitGitGadget/mailing-list-mirror.js @@ -1,65 +1,113 @@ -const https = require('https') +const { httpsRequestBuffer } = require('./https-request') -const parseRefAdvertisement = (body, ref, url) => { +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 + 4 <= body.length) { - const packetHeader = body.slice(offset, offset + 4) - if (!/^[0-9a-f]{4}$/i.test(packetHeader)) break + 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(packetHeader, 16) + const length = Number.parseInt(header, 16) + offset += 4 if (length === 0 || length === 1 || length === 2) { - offset += 4 + packets.push({ length }) continue } - if (length < 4 || offset + length > body.length) break + // 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 line = body.slice(offset + 4, offset + length).split('\0', 1)[0].trim() - const match = line.match(/^([0-9a-f]{40,64})\s+(.+)$/) - if (match && match[2] === ref) return match[1] - offset += length +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 (url, ref) => { +const getRef = async (context, url, ref) => { const { hostname, pathname } = new URL(url) - const requestPath = `${pathname.replace(/\/$/, '')}/info/refs?service=git-upload-pack` - const body = await new Promise((resolve, reject) => { - const request = https.request({ - hostname, - method: 'GET', - path: requestPath, - headers: { - 'Git-Protocol': 'version=1', - 'User-Agent': 'GitGitGadget/1.0' - } - }, response => { - const chunks = [] - response.on('data', chunk => chunks.push(chunk)) - response.on('error', reject) - response.on('end', () => { - if (response.statusCode !== 200) { - reject(new Error(`Could not read ${url}: HTTP ${response.statusCode}`)) - return - } - resolve(Buffer.concat(chunks).toString('utf8')) - }) - }) - request.on('error', reject) - request.setTimeout(30_000, () => request.destroy(new Error(`Timed out reading ${url}`))) - request.end() - }) + 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) - return parseRefAdvertisement(body, ref, 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 => { +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.pathname = `${sourceURL.pathname.replace(/\/+$/, '')}/${epoch}` sourceURL.search = '' sourceURL.hash = '' const mirrorURL = new URL(config.mailrepo.mirrorURL) @@ -70,10 +118,10 @@ const isUpToDate = async config => { if (!mirrorURL.pathname.endsWith('.git')) mirrorURL.pathname += '.git' const [sourceOID, mirrorOID] = await Promise.all([ - getRef(sourceURL.href, `refs/heads/${config.mailrepo.branch}`), - getRef(mirrorURL.href, config.mailrepo.mirrorRef || `refs/heads/lore-${epoch}`) + 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, parseRefAdvertisement } +module.exports = { isUpToDate, parseCapabilities, parsePacketLines, parseRefAdvertisement } diff --git a/__tests__/https-request.test.js b/__tests__/https-request.test.js new file mode 100644 index 0000000..15cb51a --- /dev/null +++ b/__tests__/https-request.test.js @@ -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)) +}) diff --git a/__tests__/mailing-list-mirror.test.js b/__tests__/mailing-list-mirror.test.js index e2162ae..ae6cd5b 100644 --- a/__tests__/mailing-list-mirror.test.js +++ b/__tests__/mailing-list-mirror.test.js @@ -1,35 +1,20 @@ -jest.mock('https') -const https = require('https') -const { isUpToDate, parseRefAdvertisement } = require('../GitGitGadget/mailing-list-mirror') -const EventEmitter = require('events') - -let responses - -https.request = jest.fn((options, callback) => { - const { body, statusCode = 200 } = responses.shift() - const request = new EventEmitter() - request.setTimeout = jest.fn() - request.end = () => { - const response = new EventEmitter() - response.statusCode = statusCode - callback(response) - response.emit('data', Buffer.from(body)) - response.emit('end') - } - return request -}) - -const packet = line => `${(Buffer.byteLength(line) + 4).toString(16).padStart(4, '0')}${line}` +const mockHttpsRequestBuffer = jest.fn() +jest.mock('../GitGitGadget/https-request', () => ({ httpsRequestBuffer: mockHttpsRequestBuffer })) -const advertisement = (refs, capabilities = 'multi_ack side-band') => [ - packet('# service=git-upload-pack\n'), - '0000', - packet('version 1\n'), - ...refs.map(([oid, ref], index) => packet(`${oid} ${ref}${index === 0 ? `\0${capabilities}` : ''}\n`)), - '0000' -].join('') +const { isUpToDate, parseRefAdvertisement } = require('../GitGitGadget/mailing-list-mirror') -const makeConfig = () => ({ +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', @@ -39,87 +24,32 @@ const makeConfig = () => ({ } }) -beforeEach(() => { - jest.clearAllMocks() - responses = [] -}) +beforeEach(() => jest.clearAllMocks()) -test('read a ref from a Git protocol v1 advertisement', () => { - const head = 'a'.repeat(40) - const master = 'b'.repeat(40) - const mirror = 'c'.repeat(40) - const body = advertisement([ - [head, 'HEAD'], - [master, 'refs/heads/master'], - [mirror, 'refs/heads/lore-1'] - ]) - - expect(parseRefAdvertisement(body, 'refs/heads/lore-1', 'https://example.com/repo.git')).toBe(mirror) -}) +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`) + }) -test('reject an advertisement without the requested ref', () => { - const body = advertisement([['a'.repeat(40), 'refs/heads/master']]) + await expect(isUpToDate(config())).resolves.toBe(true) - expect(() => parseRefAdvertisement(body, 'refs/heads/lore-1', 'https://example.com/repo.git')) - .toThrow('Could not find refs/heads/lore-1') + 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('reject a malformed packet advertisement', () => { - expect(() => parseRefAdvertisement('zzzz', 'refs/heads/master', 'https://example.com/repo.git')) - .toThrow('Could not find refs/heads/master') -}) - -test('compare the lore and mirror refs when URLs lack or have trailing slashes', async () => { - const source = 'a'.repeat(40) - responses = [ - { body: advertisement([[source, 'refs/heads/master']]) }, - { body: advertisement([[source, 'refs/heads/lore-1']]) } - ] - - await expect(isUpToDate(makeConfig())).resolves.toBe(true) - - expect(https.request.mock.calls.map(([options]) => [options.hostname, options.path])).toEqual([ - ['lore.kernel.org', '/git/1/info/refs?service=git-upload-pack'], - ['github.com', '/gitgitgadget/git-mailing-list-mirror.git/info/refs?service=git-upload-pack'] +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') ]) - for (const [options] of https.request.mock.calls) { - expect(options.headers['Git-Protocol']).toBe('version=1') - expect(options.headers['User-Agent']).toBe('GitGitGadget/1.0') - } -}) - -test('report when the GitHub mirror is behind lore', async () => { - responses = [ - { body: advertisement([['a'.repeat(40), 'refs/heads/master']]) }, - { body: advertisement([['b'.repeat(40), 'refs/heads/lore-1']]) } - ] - - await expect(isUpToDate(makeConfig())).resolves.toBe(false) -}) - -test('fail when either ref advertisement cannot be fetched', async () => { - responses = [ - { body: 'Forbidden', statusCode: 403 }, - { body: advertisement([['a'.repeat(40), 'refs/heads/lore-1']]) } - ] - - await expect(isUpToDate(makeConfig())).rejects.toThrow('HTTP 403') -}) - -test('reject non-HTTPS source and mirror URLs', async () => { - const config = makeConfig() - config.mailrepo.mirrorURL = 'http://github.com/gitgitgadget/git-mailing-list-mirror' - - await expect(isUpToDate(config)).rejects.toThrow('must use HTTPS') - - expect(https.request).not.toHaveBeenCalled() -}) - -test('skip ref polling when no GitHub mirror is configured', async () => { - const config = makeConfig() - delete config.mailrepo.mirrorURL - - await expect(isUpToDate(config)).resolves.toBe(true) - expect(https.request).not.toHaveBeenCalled() + expect(parseRefAdvertisement(body, 'refs/heads/lore-1', 'https://example.com/repo.git')).toBe(wanted) }) From 0972b325aae62cc3cd1286d9d52695effc57df83 Mon Sep 17 00:00:00 2001 From: Alessio Attilio Date: Fri, 4 Dec 2026 18:49:07 +0100 Subject: [PATCH 7/7] fix: throttle mailing-list mirror polling --- GitGitGadget/sync-mailing-list-mirror.js | 31 ++++++--- README.md | 2 +- __tests__/sync-mailing-list-mirror.test.js | 76 +++++++++------------- sync-mailing-list-mirror/function.json | 2 +- 4 files changed, 52 insertions(+), 59 deletions(-) diff --git a/GitGitGadget/sync-mailing-list-mirror.js b/GitGitGadget/sync-mailing-list-mirror.js index 43d0bcd..86cf745 100644 --- a/GitGitGadget/sync-mailing-list-mirror.js +++ b/GitGitGadget/sync-mailing-list-mirror.js @@ -1,34 +1,45 @@ const { isUpToDate } = require('./mailing-list-mirror') -module.exports = async context => { +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)) { + if (await isUpToDate(config, context)) { context.log('Mailing-list mirror is up to date') return } const { owner, name } = config.workflowsRepo - const workflow = 'sync-mailing-list-mirror.yml' 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) const { listWorkflowRuns, triggerWorkflowDispatch } = require('./trigger-workflow-dispatch') - for (const status of ['queued', 'in_progress']) { - const runs = await listWorkflowRuns(context, token, owner, name, workflow, 'main', status) - if (runs.length) { - context.log(`Skipping mirror sync; a run is already ${status}`) - return - } + 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, workflow, 'main') + 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 diff --git a/README.md b/README.md index 7af7662..a5ffa8b 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ You can also run/debug it via VS Code, there is a default configuration called " ### Keeping the mailing-list mirror current -The `sync-mailing-list-mirror` timer checks lore.kernel.org and the GitHub mirror once a minute. It dispatches the existing mirror workflow only when their advertised refs differ and skips the dispatch while another mirror run is queued or running. The workflow's five-minute schedule remains as a fallback. +The `sync-mailing-list-mirror` timer checks lore.kernel.org and the GitHub mirror every five minutes. It dispatches the existing mirror workflow only when their advertised refs differ, skips the dispatch while another mirror run is queued or running, and waits five minutes after a completed run before dispatching again. The workflow's five-minute schedule remains as a fallback. The timer uses the existing `AzureWebJobsStorage` setting for its schedule and lock. Delivery time still depends on lore.kernel.org publishing the message and Azure running the timer. diff --git a/__tests__/sync-mailing-list-mirror.test.js b/__tests__/sync-mailing-list-mirror.test.js index 691d74f..bb2abdf 100644 --- a/__tests__/sync-mailing-list-mirror.test.js +++ b/__tests__/sync-mailing-list-mirror.test.js @@ -17,8 +17,7 @@ jest.mock('../GitGitGadget/trigger-workflow-dispatch', () => ({ })) const syncMailingListMirror = require('../GitGitGadget/sync-mailing-list-mirror') - -const makeContext = () => ({ log: jest.fn() }) +const context = () => ({ log: jest.fn() }) beforeEach(() => { jest.clearAllMocks() @@ -29,54 +28,37 @@ beforeEach(() => { mockTriggerWorkflowDispatch.mockResolvedValue({ html_url: 'https://github.com/run/1' }) }) -test('does not dispatch a sync when the mirror is current', async () => { - const context = makeContext() - - await syncMailingListMirror(context) - - expect(mockGetInstallationIdForRepo).not.toHaveBeenCalled() - expect(mockTriggerWorkflowDispatch).not.toHaveBeenCalled() - expect(context.log).toHaveBeenCalledWith('Mailing-list mirror is up to date') -}) - -test('dispatches a sync when lore is ahead and no run is active', async () => { - const context = makeContext() - mockIsUpToDate.mockResolvedValue(false) - - await syncMailingListMirror(context) - - expect(mockListWorkflowRuns).toHaveBeenCalledTimes(2) - expect(mockTriggerWorkflowDispatch).toHaveBeenCalledWith( - context, - 'installation-token', - 'gitgitgadget-workflows', - 'gitgitgadget-workflows', - 'sync-mailing-list-mirror.yml', - 'main' - ) +test('does not request a workflow run when the mirror is current', async () => { + await syncMailingListMirror(context()) + expect(mockListWorkflowRuns).not.toHaveBeenCalled() }) -test.each(['queued', 'in_progress'])('does not dispatch while a sync is %s', async status => { - const context = makeContext() +test.each(['queued', 'in_progress', 'completed'])( + 'does not dispatch while a run is active or recently completed (%s)', + async status => { + const ctx = context() + mockIsUpToDate.mockResolvedValue(false) + mockListWorkflowRuns.mockResolvedValue([{ + status, + updated_at: new Date().toISOString() + }]) + + await syncMailingListMirror(ctx) + + expect(mockListWorkflowRuns).toHaveBeenCalledTimes(1) + expect(mockTriggerWorkflowDispatch).not.toHaveBeenCalled() + } +) + +test('dispatches once when lore is ahead and the last run is old', async () => { + const ctx = context() mockIsUpToDate.mockResolvedValue(false) - mockListWorkflowRuns.mockImplementation(async (_context, _token, _owner, _repo, _workflow, _branch, queriedStatus) => { - return queriedStatus === status ? [{ status }] : [] - }) - - await syncMailingListMirror(context) - - expect(mockTriggerWorkflowDispatch).not.toHaveBeenCalled() - expect(context.log).toHaveBeenCalledWith(`Skipping mirror sync; a run is already ${status}`) -}) - -test('propagates a failure to read the mailing-list refs', async () => { - const context = makeContext() - const error = new Error('lore is unavailable') - mockIsUpToDate.mockRejectedValue(error) + mockListWorkflowRuns.mockResolvedValue([ + { status: 'completed', updated_at: new Date(Date.now() - 10 * 60 * 1000).toISOString() } + ]) - await expect(syncMailingListMirror(context)).rejects.toThrow('lore is unavailable') + await syncMailingListMirror(ctx) - expect(mockGetInstallationIdForRepo).not.toHaveBeenCalled() - expect(mockTriggerWorkflowDispatch).not.toHaveBeenCalled() - expect(context.log).toHaveBeenCalledWith('Caught exception ', error) + expect(mockListWorkflowRuns).toHaveBeenCalledTimes(1) + expect(mockTriggerWorkflowDispatch).toHaveBeenCalledTimes(1) }) diff --git a/sync-mailing-list-mirror/function.json b/sync-mailing-list-mirror/function.json index d257407..e8a1025 100644 --- a/sync-mailing-list-mirror/function.json +++ b/sync-mailing-list-mirror/function.json @@ -4,7 +4,7 @@ "name": "timer", "type": "timerTrigger", "direction": "in", - "schedule": "0 */1 * * * *" + "schedule": "0 */5 * * * *" } ] }