OverviewFilesCommitsIssuesDocsReleasesPeers

pear-git-v3 / lib / services / repo-created-entry.js

50 lines · javascript ref:
/**
 * maybeAppendCreatedEntry — decide whether a repo's "created" RepoEventLog
 * entry needs (re-)appending on a serve event, and do it.
 *
 * Extracted from startPearGit's `sync.on('serve')` handler so the null-key →
 * keyed re-emit is unit-testable in isolation.
 *
 * The "created" entry conveys the repo's tracker bootstrap key
 * (issueBootstrapKey) so mirrors can mount its issue/refs tracker. The key may
 * not be registered yet at first serve (an ordering race between repo-serve and
 * tracker-key registration) → the entry ships null. Without re-emitting a keyed
 * entry once the key exists, a mirror that replicated the null entry binds no
 * tracker and forks a split-brain island forever (2026-07-05 hyper-proto-peer).
 *
 * Mutates the per-boot dedup sets loggedNames / keyedNames. Returns
 * { appended, keyed } for observability + testing.
 *
 * @param {object}   args
 * @param {string}   args.name           repo name
 * @param {object}   args.syncServer     has info(name) → { head }
 * @param {object}   args.issueRegistry  has async keys() → { repos: { <name>: <hex> } }
 * @param {object}   args.repoEventLog    has async append({ op, name, head, issueBootstrapKey })
 * @param {Set}      args.loggedNames     names for which a created entry was appended
 * @param {Set}      args.keyedNames      names for which a KEYED entry was appended
 * @returns {Promise<{ appended: boolean, keyed: boolean }>}
 */
export async function maybeAppendCreatedEntry ({ name, syncServer, issueRegistry, repoEventLog, loggedNames, keyedNames }) {
  const firstServe = !loggedNames.has(name)
  if (firstServe) loggedNames.add(name) // sync guard vs duplicate first-appends
  else if (keyedNames.has(name)) return { appended: false, keyed: true } // key already conveyed

  const info = syncServer.info(name)
  const head = info && info.head ? info.head : ''
  const issueKeysMap = (await issueRegistry.keys()).repos || {}
  const issueKeyHex = issueKeysMap[name] || null
  const issueKey = issueKeyHex ? Buffer.from(issueKeyHex, 'hex') : null

  // A re-serve only needs an append if the key is now available and hasn't
  // already been conveyed (guard against a racing serve that keyed it first).
  if (!firstServe && (!issueKey || keyedNames.has(name))) return { appended: false, keyed: false }
  if (issueKey) keyedNames.add(name)
  await repoEventLog.append({
    op: 0, // created (re-emitted with the key if it landed after first serve)
    name,
    head,
    issueBootstrapKey: issueKey
  })
  return { appended: true, keyed: !!issueKey }
}