Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions GitGitGadget/mailing-list-mirror.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
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`
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()
})

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(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.href, `refs/heads/${config.mailrepo.branch}`),
getRef(mirrorURL.href, config.mailrepo.mirrorRef || `refs/heads/lore-${epoch}`)
])
return sourceOID === mirrorOID
}

module.exports = { isUpToDate, parseRefAdvertisement }
34 changes: 34 additions & 0 deletions GitGitGadget/sync-mailing-list-mirror.js
Original file line number Diff line number Diff line change
@@ -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
}
}
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
125 changes: 125 additions & 0 deletions __tests__/mailing-list-mirror.test.js
Original file line number Diff line number Diff line change
@@ -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()
})
82 changes: 82 additions & 0 deletions __tests__/sync-mailing-list-mirror.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
10 changes: 10 additions & 0 deletions sync-mailing-list-mirror/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"bindings": [
{
"name": "timer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */1 * * * *"
}
]
}
3 changes: 3 additions & 0 deletions sync-mailing-list-mirror/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const syncMailingListMirror = require('../GitGitGadget/sync-mailing-list-mirror')

module.exports = async context => syncMailingListMirror(context)
Loading