openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 12.8 kB
JavaScript
import{o as resolveGlobalSingleton}from"./global-singleton-DolL9xGt.mjs";import{p as toErrorObject}from"./error-coercion-DlKnt6w-.mjs";import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import"./abort-signal-BKkRe6pu.mjs";import{t as pruneMapToMaxSize}from"./map-size-DLQqorvK.mjs";import{t as observeOwnedDirectory}from"./owned-directory-observation-BDuOMAKd.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as monotonicNow}from"./monotonic-time-DjtFTu2s.mjs";import{C as runWithGatewayDetachedWorkContinuation}from"./gateway-work-admission-CnMW3_qr.mjs";import{t as runGitWorkerOperation}from"./git-worker-CBvkg-PR.mjs";import{n as startDiffReadTiming,t as addDiffReadDurations}from"./diff-read-timing-C4RhXe71.mjs";import path from"node:path";import{performance}from"node:perf_hooks";
//!src/infra/git-branch-read-cache.ts
function createBranchReadCache(e){const t=/* @__PURE__ */ new Map;return{async read(n,r={}){r.signal?.throwIfAborted();if(!r.snapshot){const{observation:e,...t}=await runGitWorkerOperation({type:`repository.branches`,input:n},r);return t}const i=JSON.stringify([n.repoRoot,e()]);let a=t.get(i);if(!a){if(t.size>=64){const e=[...t].find(([,e])=>!e.pending);if(e){e[1].watches.forEach(e=>e.close());t.delete(e[0])}else return{branches:[],branchesUnavailable:true}}a={dirty:true,retryAt:0,watches:[]};t.set(i,a)}const o=a;if(!a.pending&&(r.refresh||a.dirty||a.retryAt>0&&monotonicNow()>=a.retryAt)){a.dirty=false;const e=new AbortController;a.controller=e;a.pending=runWithGatewayDetachedWorkContinuation(async()=>{const t=setTimeout(()=>e.abort(),2e3);try{const{observation:t,...r}=await runGitWorkerOperation({type:`repository.branches`,input:{repoRoot:n.repoRoot,includeRepositoryStatus:true}},{signal:e.signal});const i=JSON.stringify(t);if(!o.watches.length||o.observation!==i){o.watches.forEach(e=>e.close());o.watches=[];o.observation=i;const invalidate=(e,t)=>{if(t||o.watches.some(e=>!e.isWatching()))o.dirty=true};const e=new Set(t?[t.gitDir,t.commonDir]:[path.join(n.repoRoot,`.git`)]);for(const t of e)o.watches.push(observeOwnedDirectory(t,(e,t)=>{if(!e||/^(HEAD|packed-refs|config|config.worktree|commondir|refs|reftable)$/.test(e))invalidate(e,t)}));if(t){for(let e=path.resolve(n.repoRoot);;e=path.dirname(e)){o.watches.push(observeOwnedDirectory(e,(e,t)=>{if(!e||e===`.git`)invalidate(e,t)}));if(e===t.root||path.dirname(e)===e)break}o.watches.push(observeOwnedDirectory(path.join(t.commonDir,`refs`),invalidate,{recursive:true}));o.watches.push(observeOwnedDirectory(path.join(t.commonDir,`reftable`),invalidate,{recursive:true}))}}o.value=r.repositoryStatus===`unavailable`||r.branchesUnavailable?{...o.value??r,branchesUnavailable:true}:r;o.retryAt=r.repositoryStatus===`not_git`||r.repositoryStatus===`unavailable`||r.branchesUnavailable?monotonicNow()+5e3:0}catch{o.value={...o.value??{branches:[],repositoryStatus:`unavailable`},branchesUnavailable:true};o.retryAt=monotonicNow()+5e3}finally{clearTimeout(t);o.pending=void 0;o.controller=void 0}return o.value},`runtime:branch-discovery`)}if(a.pending&&r.onRefresh)a.pending.then(r.onRefresh).catch(()=>{});const s={...a.value??{branches:[]},...a.pending?{refreshing:true}:{}};if(n.includeRepositoryStatus)return s;const{repositoryStatus:c,...l}=s;return l},async close(){for(const e of t.values())e.controller?.abort();await Promise.allSettled([...t.values()].flatMap(e=>e.pending?[e.pending]:[]));for(const e of t.values())e.watches.forEach(e=>e.close());t.clear()}}}
//!src/infra/git-read-cache.ts
const MAX_CACHED_CHECKOUTS=1e3;const log=createSubsystemLogger(`git/read`);function gitEnvironment(){return Object.keys(process.env).filter(e=>/^(GIT_|HOME$|XDG_CONFIG_HOME$|PATH$|SUDO_UID$)/i.test(e)).toSorted((e,t)=>e.localeCompare(t)).map(e=>[e,process.env[e]])}function diffRevisionMissReason(e,t){try{const n=JSON.parse(e??`null`);const r=JSON.parse(t??`null`);if(n&&r){for(const[e,t]of[[`head`,`revision-changed-head`],[`index`,`revision-changed-index`],[`untrackedSet`,`revision-changed-untracked-set`],[`worktreeMtime`,`revision-changed-worktree-mtime`]])if(n[e]!==r[e])return t}}catch{}return`revision-changed-metadata`}function createReadCache(e,t,n,r,i=()=>true,a=MAX_CACHED_CHECKOUTS,o){const s=typeof t===`number`?t:t.milliseconds;const c=typeof t!==`number`&&t.joinPending;const l=/* @__PURE__ */ new Map;const u=/* @__PURE__ */ new Map;const d=/* @__PURE__ */ new Set;const f=/* @__PURE__ */ new Map;let p=Promise.resolve();let m=false;let h=0;const releasePoll=(e,t)=>{if(l.get(e)!==t||!t.poll)return;delete t.poll;h--;if(!t.entry)l.delete(e)};const remove=(e,t)=>{const n=l.get(e);if(n?.entry===t){delete n.entry;if(!n.poll)l.delete(e)}};const read=async(h,g={},_,v)=>{try{var y=_usingCtx();g.signal?.throwIfAborted();const b=y.u(o?startDiffReadTiming(`checkout.diff`):void 0);const x=b??g.diffTiming;const S=x?performance.now():0;const C=_??gitEnvironment();const w=v??JSON.stringify([h,C]);let T=l.get(w)?.entry;const E=!g.refresh&&(T?.retryAt??0)>monotonicNow();let D=E?T.revision:void 0;let O;if(n&&!E){const e=n(h,T?.value);const t=JSON.stringify([e,C]);let r=f.get(t);if(!r){const n=new AbortController;const i=x?{durations:{}}:void 0;r={controller:n,promise:runGitWorkerOperation({type:`checkout.revision`,input:e},{signal:n.signal,diffTiming:i}).finally(()=>{f.delete(t)}),timing:i};f.set(t,r)}O=await racePromiseWithAbortSignal(r.promise,g.signal,e=>toErrorObject(e.reason,`Git read aborted`));D=O?.key??null;if(x&&r.timing){addDiffReadDurations(x,r.timing);x.revisionUnavailableReason=r.timing.revisionUnavailableReason}}if(x)x.durations[`cache-validate`]=performance.now()-S;const k=typeof t!==`number`&&typeof D===`string`?Number.POSITIVE_INFINITY:s;g.signal?.throwIfAborted();if(m)throw new Error(`Git reads are unavailable while the Gateway is restarting`);T=l.get(w)?.entry;const A=T;const j=u.delete(w);let M=!T?.pending;if(g.refresh&&(D===null||T?.retryAt!==void 0)||!T||T.revision!==D||T.expiresAt<=monotonicNow()&&(!(r||c)||!T.pending)){if(r&&d.size>=MAX_CACHED_CHECKOUTS)return T?.value??r.empty();M=false;const t=x?{durations:{}}:void 0;const n=p;const a=new AbortController;const o={revision:D,expiresAt:k===0?Number.POSITIVE_INFINITY:monotonicNow()+(D===null?Math.min(k,75e3):k),controller:a,pending:true,timing:t,value:T?.value,promise:Promise.resolve().then(()=>r?runWithGatewayDetachedWorkContinuation(async()=>{await n;a.signal.throwIfAborted();return e(h,a.signal,t,O)},`runtime:project-discovery`):e(h,a.signal,t,O))};d.add(o);o.promise=o.promise.then(e=>{o.pending=false;d.delete(o);a.signal.throwIfAborted();o.value=e;if(r)o.expiresAt=monotonicNow()+s;const t=i(e);if(typeof t===`number`)o.retryAt=o.expiresAt=monotonicNow()+t;else if(k===0||!t)remove(w,o);else if(c&&D===null)o.retryAt=o.expiresAt;return e},e=>{o.pending=false;d.delete(o);if(r)o.expiresAt=monotonicNow()+s;else{o.expiresAt=0;remove(w,o)}throw e});if(r)p=o.promise.catch(()=>{if(!a.signal.aborted)log.warn(`Repository discovery refresh failed; retaining the previous project snapshot`)});T=o}const N=l.get(w)??{};N.entry=T;l.delete(w);l.set(w,N);for(const[e,t]of l){if(l.size<=a)break;if(t.poll){if(t.poll.pending||t.poll.expiresAt>monotonicNow())continue;releasePoll(e,t)}l.delete(e);u.set(e,true)}pruneMapToMaxSize(u,a);const P=r?T.value??r.empty():await racePromiseWithAbortSignal(T.promise,g.signal,e=>toErrorObject(e.reason,`Git read aborted`));if(x){x.outcome=M?`cache-hit`:`cache-miss`;x.missReason=M?void 0:D===null?x.revisionUnavailableReason??`no-revision`:!A?j?`evicted`:`cold`:A.revision!==D?diffRevisionMissReason(A.revision,D):`pending`;if(!M&&T.timing)addDiffReadDurations(x,T.timing)}if(b&&g.diffTiming){addDiffReadDurations(g.diffTiming,b);g.diffTiming.outcome=b.outcome;g.diffTiming.missReason=b.missReason}return P}catch(e){y.e=e}finally{y.d()}};return{async read(e,t={}){t.signal?.throwIfAborted();if(m)throw new Error(`Git reads are unavailable while the Gateway is restarting`);if(!o||!t.poll)return read(e,t);const computing=()=>{if(t.diffTiming){t.diffTiming.outcome=`cache-miss`;t.diffTiming.missReason=`pending`}return o.empty()};const n=gitEnvironment();const r=JSON.stringify([e,n]);const i=l.get(r)??{};if(i.poll&&!i.poll.pending&&i.poll.expiresAt<=monotonicNow())releasePoll(r,i);let s=i.poll;if(!s&&i.entry?.value)return read(e,t,n,r);if(!s){if(h>=a){for(const[e,t]of l)if(t.poll&&!t.poll.pending&&t.poll.expiresAt<=monotonicNow())releasePoll(e,t)}if(h>=a)return computing();const n=new AbortController;const o=runWithGatewayDetachedWorkContinuation(()=>read(e,{...t,signal:n.signal,diffTiming:void 0}),`runtime:checkout-diff`);s={promise:o,controller:n,pending:true,expiresAt:Number.POSITIVE_INFINITY};const c=s;const settled=()=>{c.pending=false;c.expiresAt=monotonicNow()+1e3};o.then(settled,settled);i.poll=s;h++;l.set(r,i)}let c=false;let u;try{const e=await racePromiseWithAbortSignal(s.pending?Promise.race([s.promise,new Promise(e=>{u=setTimeout(()=>{c=true;e(computing())},2e3)})]):s.promise,t.signal,e=>toErrorObject(e.reason,`Git read aborted`));if(!c&&t.diffTiming){t.diffTiming.outcome=`cache-hit`;t.diffTiming.missReason=void 0}return e}finally{clearTimeout(u)}},async close(){m=true;for(const{controller:e}of f.values())e.abort();const e=[...d];for(const t of e){t.expiresAt=0;t.controller.abort()}const t=Array.from(l.values()).flatMap(e=>e.poll?[e.poll]:[]);for(const e of t)e.controller.abort();l.clear();h=0;u.clear();await Promise.allSettled([...Array.from(f.values(),e=>e.promise),...e.map(e=>e.promise),...t.map(e=>e.promise)])}}}function createDiffReadCache(e,t=MAX_CACHED_CHECKOUTS){const revisionInput=(e,t)=>({root:e.cwd,scope:`diff`,summaryOnly:e.summaryOnly===true,refreshIndex:e.refreshIndex===true,paths:t?.files.flatMap(e=>e.oldPath?[e.path,e.oldPath]:[e.path]).toSorted()});return createReadCache((e,t,n,r)=>runGitWorkerOperation({type:`checkout.diff`,input:{...e,worktreeStatus:r?.worktreeStatus}},{signal:t,diffTiming:n}),e,revisionInput,void 0,e=>e.unavailableReason===`not_git`?1e3:!e.unavailableReason,t,{empty:()=>({files:[],additions:0,deletions:0,computing:true})})}function createReadCaches(){const e=createReadCache((e,t)=>runGitWorkerOperation({type:`pull-request.branch-comparison`,input:e},{signal:t}),Number.POSITIVE_INFINITY,({root:e,branch:t,defaultBranch:n})=>({root:e,branch:t,defaultBranch:n,scope:`refs`}),void 0,e=>e.complete);return{comparisons:e,identities:createReadCache((e,t)=>runGitWorkerOperation({type:`repository.identities`,input:e},{signal:t}),6e4,void 0,{empty:()=>[]}),context:createReadCache((e,t)=>runGitWorkerOperation({type:`checkout.context`,input:e},{signal:t}),Number.POSITIVE_INFINITY,({root:e})=>({root:e,scope:`context`})),branchFacts:createReadCache(async(t,n)=>{try{const{refreshIndex:r,...i}=t;const a=await e.read(i,{signal:n,refresh:true});return await runGitWorkerOperation({type:`pull-request.branch-facts`,input:{...t,comparison:a}},{signal:n})}catch{n.throwIfAborted();log.warn(`PR comparison unavailable; fetch repository history and retry. Dependent comparisons skipped.`);return{creatable:false,stats:null}}},3e5,({root:e,branch:t,defaultBranch:n})=>({root:e,branch:t,defaultBranch:n,scope:`worktree`})),diff:createDiffReadCache({milliseconds:0},32),diffSummary:createDiffReadCache({milliseconds:1e4,joinPending:true}),branches:createBranchReadCache(gitEnvironment),baseline:createReadCache((e,t)=>runGitWorkerOperation({type:`checkout.baseline`,input:e},{signal:t}),0)}}function runtime(){return resolveGlobalSingleton(Symbol.for(`openclaw.gitReadCache`),()=>({}),e=>{e.closing??=Promise.resolve().then(async()=>{const t=e.caches;e.caches=void 0;if(t)await Promise.all(Object.values(t).map(e=>e.close()))}).finally(()=>{e.closing=void 0});return e.closing})}function runGitReadOperation(e,t){const n=runtime();if(n.closing)return Promise.reject(/* @__PURE__ */ new Error(`Git reads are unavailable while the Gateway is restarting`));const r=n.caches??=createReadCaches();const{context:i,branchFacts:a,branches:o,baseline:s,identities:c}=r;switch(e.type){case`repository.identities`:return c.read(e.input,t);case`checkout.revision`:return runGitWorkerOperation(e,t);case`checkout.context`:return i.read(e.input,t);case`pull-request.branch-facts`:return a.read(e.input,t);case`checkout.diff`:return readDiff(e.input.summaryOnly?r.diffSummary:r.diff,e.input,t);case`repository.branches`:return o.read(e.input,t);case`checkout.baseline`:return s.read(e.input,t)}throw new Error(`Unsupported Git read operation`)}async function readDiff(e,t,n){const r=await e.read(t,n);return{...r,files:r.files.map(e=>({...e})),...r.commits?{commits:r.commits.map(e=>({...e}))}:{},...r.mergeBase?{mergeBase:{...r.mergeBase}}:{}}}export{runGitReadOperation as t};