Skip to content
Draft
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
46 changes: 32 additions & 14 deletions GitGitGadget/https-request.js
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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,
Expand All @@ -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) {
Expand All @@ -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}`)
Expand All @@ -84,5 +101,6 @@ const doesURLReturn404 = async url => {

module.exports = {
httpsRequest,
httpsRequestBuffer,
doesURLReturn404
}
}
127 changes: 127 additions & 0 deletions GitGitGadget/mailing-list-mirror.js
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])
}
Comment thread
kairosci marked this conversation as resolved.
Resolved
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 }
45 changes: 45 additions & 0 deletions GitGitGadget/sync-mailing-list-mirror.js
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)
Comment thread
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
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 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.

## 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
35 changes: 35 additions & 0 deletions __tests__/https-request.test.js
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))
})
55 changes: 55 additions & 0 deletions __tests__/mailing-list-mirror.test.js
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)
})
Loading
Loading