openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2 lines • 2.33 kB
JavaScript
//!extensions/x/src/guest-usage.ts
const DAY_MS=864e5;const MAX_AUTHOR_DAYS=1e4;const MAX_X_GUEST_MENTIONS_PER_AUTHOR_PER_DAY=1e3;var XGuestUsageUnavailableError=class extends Error{constructor(e,t){super(e,t);this.name=`XGuestUsageUnavailableError`}};function accountDayPrefix(e,t=Date.now()){return`${encodeURIComponent(e)}:${new Date(t).toISOString().slice(0,10)}:`}function openXGuestUsage(e){const t=e.state.openKeyedStore({namespace:`x.guest-usage`,maxEntries:MAX_AUTHOR_DAYS,overflowPolicy:`reject-new`,defaultTtlMs:2*DAY_MS});return{async admit(e){const n=Date.now();const r=accountDayPrefix(e.accountId,n);const assertCurrent=()=>{e.assertCurrent();if(accountDayPrefix(e.accountId)!==r)throw new Error(`X guest usage day changed during admission; retrying mention`)};const i=t.withCurrent({assertCurrent});const a=`${r}${e.authorId}`;let o=await i.observe(a);if(e.limit>0){if((await Promise.all([1,2].map(t=>i.lookup(`${accountDayPrefix(e.accountId,n-t*DAY_MS)}${e.authorId}`)))).some(t=>t?.admittedPostIds.includes(e.postId))){assertCurrent();return true}}for(;;){assertCurrent();const t=o.value??{admittedPostIds:[],rateLimited:0,recentRejectedPostIds:[]};if(e.limit>0&&t.admittedPostIds.includes(e.postId))return true;const n=t.admittedPostIds.length<e.limit;if(!n&&t.recentRejectedPostIds.includes(e.postId))return false;const r=n?{...t,admittedPostIds:[...t.admittedPostIds,e.postId]}:{...t,rateLimited:t.rateLimited+1,recentRejectedPostIds:[...t.recentRejectedPostIds,e.postId].slice(-128)};try{const e=await i.compareAndApply(a,o.comparison,{operation:`update`,action:`set`,value:r});if(e.status!==`conflict`)return n;o=e.current}catch(e){if(e instanceof Error&&`code`in e&&e.code===`PLUGIN_STATE_LIMIT_EXCEEDED`)throw new XGuestUsageUnavailableError(`X guest mode is paused because usage accounting reached capacity; retry after retained usage expires.`,{cause:e});throw e}}},async counts(e){const n=accountDayPrefix(e);return(await t.entriesInKeyRange({keyStartInclusive:n,keyEndExclusive:`${n}\uffff`,limit:MAX_AUTHOR_DAYS})).reduce((e,t)=>({admittedToday:e.admittedToday+t.value.admittedPostIds.length,rateLimitedToday:e.rateLimitedToday+t.value.rateLimited}),{admittedToday:0,rateLimitedToday:0})}}}export{XGuestUsageUnavailableError as n,openXGuestUsage as r,MAX_X_GUEST_MENTIONS_PER_AUTHOR_PER_DAY as t};