@amalgm/live 0.2.81-main.46548901607 → 0.2.81-main.46558670594
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/apply/journey.d.ts
CHANGED
|
@@ -12,7 +12,9 @@ export type HeadOutcome = 'progress' | 'again' | {
|
|
|
12
12
|
readonly blocker?: ApplyBlocker;
|
|
13
13
|
readonly comparedAt?: number;
|
|
14
14
|
readonly advanced?: readonly string[];
|
|
15
|
+
readonly again?: true;
|
|
15
16
|
};
|
|
17
|
+
export declare function stepsAside(window: ApplyWindow, head: string): boolean;
|
|
16
18
|
export declare function outcomeOf(attempt: () => Promise<HeadOutcome>): Promise<HeadOutcome>;
|
|
17
19
|
export declare class EntityApplyJourney {
|
|
18
20
|
#private;
|
package/dist/apply/journey.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.defineProperty;var w=(l,e)=>j(l,"name",{value:e,configurable:!0});import{createApplyIntent as F,createApplyWindowIntent as x}from"./contracts.js";import{planSelectedEntityApply as E}from"./plans.js";import{Recovering as M}from"../faults/recover.js";import{groundMoved as O}from"../faults/classify.js";import{localWorkWins as S}from"../clash/local-work.js";import{selectEntityApply as P}from"./selection.js";import{isSettlement as W}from"./settling.js";import{revealOrder as D}from"./window.js";function q(l,e){return l.unit===null&&l.authorityId!==e}w(q,"stepsAside");const H=w(l=>l.kind==="captured-local"||l.kind==="rejudge","drops");function v(l){return l.kind==="retry"?{kind:"park",reason:l.reason??"machine truth is unsettled",releaseOnProgress:!1,report:!1}:l.kind==="dependency"?{kind:"park",reason:l.reason,releaseOnProgress:l.waitFor===void 0,report:!1,...l.waitFor?{dependency:l.waitFor}:{},...l.blocker?{blocker:l.blocker}:{},..."comparedAt"in l?{comparedAt:l.comparedAt}:{}}:l.kind==="conflict"?{kind:"park",reason:l.reason,releaseOnProgress:!0,report:!0}:null}w(v,"parkFor");async function B(l){try{return await l()}catch(e){return{kind:"park",reason:e instanceof Error?e.message:String(e),releaseOnProgress:!1,report:!O(e),cause:e}}}w(B,"outcomeOf");const I=w(l=>W(l.judgment)?{kind:"settled",settlement:l.judgment}:null,"settled");class C{static{w(this,"EntityApplyJourney")}#e;#a;#r;#n;constructor(e,t,i){this.#e=e,this.#a={sha256Hex:e.sha256Hex,loops:e.loops},this.#r=t,this.#n=i}targetOf(e){const t=e.members[0];return t===void 0?null:e.intent?.members.find(i=>i.entityId===t.work.entityId)?.throughSequence??(t.work.kept===null?t.work.records.at(-1)?.globalSequence:t.work.resolvedThrough)??null}async run(e,t){if(e.intent!==null)return this.#p(e,e.intent);const i={member:null};try{return await this.#d(e,t,i)}catch(a){if(i.member===null||this.#n())throw a;if(O(a))return{kind:"park",reason:a instanceof Error?a.message:String(a),releaseOnProgress:!1,report:!1};if(q(e,i.member.work.entityId))return this.alone(i.member);if(a instanceof M)return{kind:"park",reason:a.message,releaseOnProgress:!1,report:!1,dependency:{producer:"capability",entityIds:a.need.subject===null?[]:[a.need.subject.id]}};throw a}}async alone(e){const t=await this.#t(null,[e],[{kind:"settled",settlement:"waiting"}]);return t==="progress"?{kind:"alone",entityId:e.work.entityId}:t}async#d(e,t,i){const a=this.#e.newIntentId(),n=this.#e.now(),o=t(),s=new Map;for(const c of e.members){if(I(c))continue;const{work:f}=c,m=P(f,this.#a),b=F({attemptId:a,work:f,target:m.target,unit:e.unit,cutoff:e.cutoff,createdAt:n,emptied:f.entityId===o&&f.play==="enter"&&(m.target.result.type==="file.text"||m.target.result.type==="file.binary")}),k=E(f,m,this.#e.sha256Hex);s.set(f.entityId,{member:c,intent:b,plan:k,adapter:this.#e.effects.adapterFor(k.target.type),look:"safe"})}const{active:d,blocked:h}=await this.#o(e.members,s,"look",i);if(d.length===0)return h??"again";const g=d.flatMap(c=>s.get(c.work.entityId)??[]);if(g.length===0)return this.#t(null,d,d.map(c=>I(c)));const y=x({attemptId:a,authorityId:e.authorityId,unit:e.unit,cutoff:e.cutoff,createdAt:n,members:g.map(c=>c.intent)});try{const c=await this.#u(d,s,i),f=c.active.flatMap(r=>s.get(r.work.entityId)??[]);if(f.length===0)return await this.#e.effects.discard(y),c.active.length===0?c.blocked??"again":this.#t(null,c.active,c.active.map(r=>I(r)));const m=f.length===g.length?y:x({...y,members:f.map(r=>r.intent)}),b=await this.#e.effects.hold(m,f.map(r=>r.plan));let k,A;try{k=await this.#o(c.active,s,"final",i),A=await this.#c(m,k,s,t)}finally{b()}return k.unseen!==null&&k.active.length===0?this.#h(k.unseen):A}catch(c){throw await this.#e.effects.discard(y),c}}async#c(e,{active:t,blocked:i},a,n){const o=t.flatMap(r=>a.get(r.work.entityId)??[]);if(o.length===0)return await this.#e.effects.discard(e),t.length===0?i??"again":this.#t(null,t,t.map(r=>I(r)));const s=x({...e,members:o.map(r=>r.intent)}),d=o.filter(r=>r.look==="safe");if(d.length>0){if(this.#n()||o.some(p=>p.intent.emptied&&n()!==p.intent.entityId))return await this.#e.effects.discard(e),"again";const r=await this.#e.store.bindWindow(s);if(r)return await this.#e.effects.discard(e),r.kind==="stale"?"again":v({...r,comparedAt:this.#r()})}const h=new Map,g=new Map,y=w((r,p,u=null)=>{h.set(r,{kind:"owed",reason:p}),u!==null&&g.set(r,u)},"owe"),c=w(r=>v(r.kind==="dependency"?{...r,comparedAt:this.#r()}:r),"waitFrom"),{order:f,cycle:m}=D(d.map(r=>({entityId:r.intent.entityId,play:r.plan.play,type:r.plan.target.type,parentUUID:r.plan.target.parentUUID}))),b="its parent chain closes among the window's members";for(const r of m)y(r,b,{kind:"park",reason:b,releaseOnProgress:!1,report:!0});for(const r of f){const p=a.get(r),u=await p.adapter.apply.reveal(p.intent,p.plan);u&&y(r,u.reason,u.kind==="dependency"?c(u):null)}for(const r of o){const p=r.intent.entityId;if(h.has(p))continue;const u=await r.adapter.verify.verify(r.intent,r.plan);u.kind==="match"?h.set(p,{kind:"materialized"}):u.kind==="local-change"?y(p,"a person's version stands in its place"):u.kind==="rejudge"||u.kind==="missing-target"?y(p,u.kind):y(p,u.reason??u.kind,c(u))}const k=t.map(r=>I(r)??h.get(r.work.entityId));if(d.length>0)return this.#s(s,t,k,g);const A=await this.#s(null,t,k,g);return await this.#e.effects.discard(e),A}async#s(e,t,i,a){const n=await this.#t(e,t,i),o=i[0];return n!=="progress"||o.kind!=="owed"?n:{...a.get(t[0].work.entityId)??{kind:"park",reason:o.reason,releaseOnProgress:!1,report:!1,again:!0},advanced:t.filter((d,h)=>i[h].kind!=="owed").map(d=>d.work.entityId)}}async#o(e,t,i,a){const n=[];for(const o of e){const s=t.get(o.work.entityId);if(!s){n.push(o);continue}let d;try{d=await this.#i(s.intent)?{kind:"captured-local"}:i==="look"?await this.#f(s):await s.adapter.apply.guard(s.intent,s.plan,i)}catch(g){if(n.length>0&&!this.#n())return{active:n,blocked:null,unseen:null};throw a.member=o,g}if(d.kind==="local-change"||d.kind==="unsettled-ground")return{active:n,blocked:n.length===0?"again":null,unseen:s};if(H(d))return{active:n,blocked:n.length===0?"again":null,unseen:null};const h=v(d);if(h)return{active:n,blocked:h,unseen:null};s.look=d.kind,n.push(o)}return{active:n,blocked:null,unseen:null}}async#u(e,t,i){for(const[a,n]of e.entries()){const o=t.get(n.work.entityId);if(!(!o||o.look!=="safe"))try{const s=await o.adapter.apply.prepare(o.intent,o.plan);if(s)return{active:e.slice(0,a),blocked:v(s)}}catch(s){if(a>0&&!this.#n())return{active:e.slice(0,a),blocked:null};throw i.member=n,s}}return{active:[...e],blocked:null}}async#p(e,t){const i=t.members.map(n=>{const o=e.members.find(d=>d.work.entityId===n.entityId);if(!o)return null;const s=n.kept===null?o.work:{...o.work,records:[],kept:n.kept};return s.records.length===0&&s.kept===null?null:E(s,P(s,this.#a,n),this.#e.sha256Hex)}),a=await this.#e.effects.recover(t,i);if(a.length!==t.members.length)throw new Error("Apply recovery answered for a different window");return this.#t(t,e.members,e.members.map(n=>I(n)??a[t.members.findIndex(o=>o.entityId===n.work.entityId)]??{kind:"owed",reason:"not a member of the bound window"}))}async#t(e,t,i){const a=await this.#e.store.endWindow(e,t,i);if(!a)return"progress";if(a.kind!=="stale"||!a.reason)throw new Error("Apply end commit returned an unknown refusal");return"again"}async#i(e){return S(e.targetType,await this.#e.store.localWorkAfter(e.authorityId,e.entityId,e.kept??e.throughSequence))}async#f(e){const{intent:t,plan:i,adapter:a}=e,n=await a.apply.guard(t,i,"look");if(n.kind!=="local-change"&&n.kind!=="unsettled-ground")return n;const o=await this.#l(t,i);if(o.kind!=="observed")return o;const s=await a.apply.guard(t,i,"look");return s.kind==="local-change"||s.kind==="unsettled-ground"?{kind:"retry",reason:"Ground still needs observation after Detect; this member cannot reveal."}:s}async#h(e){const t=await this.#l(e.intent,e.plan);return t.kind==="captured-local"?"again":v(t.kind==="observed"?{kind:"retry",reason:"Its final guard found ground Detect had not recorded; it is judged again after Detect looks."}:t)}async#l(e,t){if(await this.#i(e))return{kind:"captured-local"};let i,a=!0;const n=await this.#e.effects.captureLocal(e,t,()=>{if(!a||i!==void 0)throw new Error("Apply capture comparison must be marked exactly once");i=this.#r()}).finally(()=>{a=!1});if(!n||!["settled","local-only","retry"].includes(n.kind))throw new Error("Apply capture returned no explicit observation outcome");if(await this.#i(e))return{kind:"captured-local"};if(n.kind==="retry")return n;if(n.kind==="local-only"){if(i===void 0)throw new Error("local-only capture requires a synchronous comparison fence");if(!n.reason||n.entityIds.length===0||n.entityIds.some(o=>!o))throw new Error("local-only capture must name the retained ground and its releasing condition");return{kind:"dependency",reason:n.reason,comparedAt:i,waitFor:{producer:"detect",entityIds:n.entityIds}}}return{kind:"observed"}}}export{C as EntityApplyJourney,B as outcomeOf,q as stepsAside};
|
package/dist/apply/rail.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var I=Object.defineProperty;var a=(d,t)=>I(d,"name",{value:t,configurable:!0});import{UUID_PATTERN as u}from"../entities/types.js";import{FetchAhead as k}from"./fetch-ahead.js";import{EntityApplyJourney as E,outcomeOf as p}from"./journey.js";import{assertApplyLaneStep as b,createApplyLane as P}from"./lane.js";import{assertApplyDependency as O,assertApplyLineStep as v,createApplyLine as S,heldWait as c,releaseApplyLine as $}from"./line.js";import{windowEndForWait as y}from"./window.js";const q=8,M=1e3,w=3e4,m=3;class U{static{a(this,"EntityApplyRail")}#t;#m;#P;#M;#_;#o;#O;#a=!1;#e=!1;#d=new Map;#s=new Map;#l={queue:[],steps:new Set};#u={queue:[],steps:new Set};#n=!1;#h=null;#p=1/0;#g=[];#A=0;#v=new Map;#y=null;constructor(t){this.#t=t,this.#m=t.concurrency??q,this.#P=t.laneConcurrency??this.#m,this.#M=t.onBackgroundError??(()=>{}),this.#_=t.onIdle??(()=>{});for(const[e,s]of[["concurrency",this.#m],["lane concurrency",this.#P]])if(!Number.isSafeInteger(s)||s<1)throw new Error(`entity Apply ${e} must be a positive integer`);this.#o=new E(t,()=>this.#A,()=>this.#e),this.#O=new k(t.cargo,{sha256Hex:t.sha256Hex,loops:t.loops})}async start(){if(this.#a)throw new Error("entity Apply rail already started");if(this.#e)throw new Error("entity Apply rail is stopped");this.#a=!0;const t=await this.#t.store.readOpenUnits();if(!Array.isArray(t)||new Set(t).size!==t.length||t.some(e=>!u.test(e)))throw new Error("entity Apply store returned an invalid open unit list");for(const e of t)this.#E(e,null);await this.#x()}fetch(t,e){return this.#a?this.#e?Promise.reject(new Error("entity Apply rail is stopped")):u.test(t)?!Number.isFinite(e.stall)||e.stall<0?Promise.reject(new Error("entity Apply fetch needs a non-negative stall")):e.emptied!==void 0&&typeof e.emptied!="boolean"?Promise.reject(new Error("entity Apply fetch emptied must be a boolean")):new Promise((s,i)=>{const r=this.#E(t,null,e.emptied===!0),n=a(()=>this.#t.schedule.schedule(e.stall,()=>{r.waiters.delete(l)&&(r.emptied&&![...r.waiters].some(o=>o.emptied)&&(r.emptied=!1),s(this.#G(r)))}),"arm");let h=n();const l={emptied:e.emptied===!0,answer:a(o=>{h.cancel(),s(o)},"answer"),fail:a(o=>{h.cancel(),i(o)},"fail"),moved:a(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(l),r.waitsOn===null&&this.#N(r),this.#r()}):Promise.reject(new Error("entity Apply fetch needs a unit UUID")):Promise.reject(new Error("entity Apply rail has not started"))}progressed(t,e){if(!u.test(t))throw new Error("entity Apply progress needs a unit UUID");if(!Number.isSafeInteger(e)||e<0)throw new Error("entity Apply progress needs a byte count");e>0&&!this.#e&&this.#b(t)}recordsAvailable(){this.#I()}localStateChanged(t){this.#c("detect",t),this.#c("apply",t),this.#I()}sendAccepted(t){this.#c("send",t),this.#I()}capabilityChanged(t){this.#c("capability",t),this.#I()}owe(t){if(t.some(e=>!u.test(e)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#a||this.#e)){for(const e of t)this.#R(e);this.#r()}}#I(){!this.#a||this.#e||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(t=>c(t.held)??[])}async flush(){if(!this.#a)throw new Error("entity Apply rail has not started");this.#e||await this.#x()}async stop(){if(this.#e)return;this.#e=!0,this.#q();for(const e of[this.#l,this.#u])for(const s of e.queue.splice(0))s.queued=!1;const t=new Error("entity Apply rail stopped before the fetch answered");for(const e of this.#s.values())for(const s of e.waiters)s.fail(t);for(this.#s.clear();this.#B()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#O.stop();for(const e of this.#g.splice(0))e.resolve()}#x(){return new Promise((t,e)=>{this.#g.push({resolve:t,reject:e}),this.#n=!0,this.#r()})}#r(){if(!this.#e){if(this.#n&&this.#h===null){this.#n=!1;const t=this.#F();this.#h=t,t.then(()=>{this.#h=null,this.#r()})}for(const[t,e]of[[this.#u,this.#P],[this.#l,this.#m]])for(;t.steps.size<e&&t.queue.length>0;){const s=t.queue.shift();s.queued=!1,this.#D(s,t)}if(this.#B()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#v.clear(),this.#z(this.#t.now())){this.#r();return}this.#$();for(const t of this.#g.splice(0))t.resolve();this.#_()}}}#B(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#d.values(),...this.#s.values()]}#k(t){return t.kind==="line"?this.#d.get(t.authorityId)===t:this.#s.get(t.unit)===t}#i(t){if(!this.#e){if(t.running){t.again=!0;return}t.queued||(t.queued=!0,(t.kind==="line"?this.#l:this.#u).queue.push(t))}}#D(t,e){t.running=!0,t.again=!1;const s=(t.kind==="line"?this.#J(t):this.#H(t)).then(i=>{t.running=!1,e.steps.delete(s),(i||t.again)&&this.#k(t)&&(t.again=!1,this.#i(t)),this.#r()});e.steps.add(s)}async#F(){try{const t=await this.#t.store.readApplyAuthorities();if(!Array.isArray(t)||new Set(t).size!==t.length||t.some(s=>typeof s!="string"||s.length===0))throw new Error("entity Apply store returned an invalid authority list");this.#p=1/0;const e=new Set(t);for(const[s,i]of this.#d)!e.has(s)&&!i.running&&!i.queued&&this.#d.delete(s);for(const s of t){let i=this.#d.get(s);i||(i=S(s),this.#d.set(s,i)),this.#i(i)}}catch(t){this.#p=this.#t.now()+w;const e=this.#g.splice(0);e.length===0&&this.#S(t);for(const s of e)s.reject(t)}}async#J(t){try{const e=t.held;if(e&&e.entityId===null&&!e.due&&e.notBefore>this.#t.now())return!1;const s=this.#A,i=await this.#t.store.readApplyWindow(t.authorityId,t.endsBefore);if(v(t.authorityId,i),this.#e)return!1;if(i.kind==="end"){t.held=null;const r=t.endsBefore!==null;return t.endsBefore=null,r}return i.window.deliverySequence!==null&&this.#O.advance(t.authorityId,i.window.deliverySequence),await this.#L(t,i.window,s)}catch(e){return this.#j(t,e),!1}}async#H(t){try{const e=t.held;if(e&&e.entityId===null&&!e.due&&e.notBefore>this.#t.now())return!1;const s=this.#A,i=await this.#t.store.readFetchWindow(t.unit,t.toPrefix?null:t.through);if(b(t.unit,i),this.#e||!this.#k(t))return!1;switch((i.kind!=="window"||i.window.intent===null)&&(t.toPrefix=!1),t.through!==null&&i.through>t.through&&t.met.clear(),t.through=Math.max(t.through??0,i.through),t.waitsOn=null,i.kind!=="window"&&(t.held=null),i.kind){case"end":return this.#f(t,{kind:"placed"}),!1;case"nowhere":return this.#f(t,{kind:"nowhere",reason:i.reason}),!1;case"root":return await this.#V(t,i.through,i.reason);case"prerequisite":return this.#X(t,i.unit,i.reason,s);case"window":return await this.#L(t,i.window,s)}}catch(e){return this.#j(t,e),!1}}async#V(t,e,s){return t.met.has(t.unit)?(this.#f(t,{kind:"held",unit:t.unit,reason:`${t.unit} entered and still not held: ${s}`}),!1):(await this.#t.effects.enterRoot(t.unit,e),this.#e||!this.#k(t)?!1:(t.through===e&&t.met.add(t.unit),this.#b(t.unit),!0))}#R(t){const e=this.#E(t,null);e.toPrefix=!0,e.met.clear(),this.#i(e)}#E(t,e,s=!1){let i=this.#s.get(t);return i?e!==null&&(i.through===null||i.through<e)&&(i.through=e,i.met.clear(),this.#i(i)):(i=P(t,e,s),this.#s.set(t,i),this.#i(i)),i}#X(t,e,s,i){if(t.met.has(e))return this.#f(t,{kind:"held",unit:e,reason:`${e} placed and still needed: ${s}`}),!1;if(!this.#T(t,e,s))return!1;const r={producer:"apply",entityIds:[e]};return t.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#W(r,i),reason:s,dependency:r},t.held.due}#N(t){const e=t.held;if(e?.dependency?.producer==="apply"){for(const s of e.dependency.entityIds)if(s!==t.unit&&!t.met.has(s)&&!this.#T(t,s,e.reason))return}}#T(t,e,s){const i=[t];let r=this.#s.get(e);for(;r&&r!==t&&!i.includes(r);)i.push(r),r=r.waitsOn===null?void 0:this.#s.get(r.waitsOn);if(r===t){for(const n of i)this.#f(n,{kind:"held",unit:e,reason:`prerequisite cycle through ${e}: ${s}`});return!1}return t.waitsOn??=e,this.#i(this.#E(e,t.through)),!0}#f(t,e){if(!this.#k(t))return;for(const i of t.waiters)i.answer(e);t.waiters.clear(),t.waitsOn=null,(e.kind==="placed"||t.held?.entityId==null)&&this.#s.delete(t.unit);const s=e.kind==="placed"||e.kind==="held"?e:{kind:"held",unit:t.unit,reason:`${t.unit} is nowhere here: ${e.reason}`};for(const i of[...this.#s.values()])if(i.waitsOn===t.unit){if(e.kind!=="placed"){this.#f(i,s);continue}i.met.add(t.unit)}e.kind==="placed"&&(this.#b(t.unit),this.#c("apply",[t.unit]))}#b(t){const e=new Map([[t,!0]]);for(const s of this.#s.values()){const i=new Set;let r=s.unit;for(;r!==null&&!e.has(r)&&!i.has(r);)i.add(r),r=this.#s.get(r)?.waitsOn??null;const n=r!==null&&e.get(r)===!0;for(const h of i)e.set(h,n);if(n)for(const h of s.waiters)h.moved()}}#G(t){let e=t;const s=new Set([t]);for(let i=t.waitsOn===null?void 0:this.#s.get(t.waitsOn);i&&!s.has(i);i=i.waitsOn===null?void 0:this.#s.get(i.waitsOn))s.add(i),e=i;return{kind:"held",unit:e.unit,reason:e.held?.reason??"still placing"}}async#L(t,e,s){const i=e.members[0]?.work.entityId??null;if(t.held&&t.held.entityId!==null&&t.held.entityId!==i&&(t.held=null),await this.#Q(t,e))return!1;let r=await p(()=>this.#o.run(e,()=>t.kind==="lane"&&t.emptied?t.unit:null));if(t.kind==="line"&&typeof r=="object"&&r.kind==="park"&&y(e,r.dependency)===null&&this.#K(t,e,r)&&(r=await p(()=>this.#o.alone(e.members[0]))),r==="progress"||typeof r=="object"&&r.kind==="alone"){if(t.kind==="line")for(const n of e.members)(n.judgment==="waiting"||r!=="progress"&&n.work.entityId===r.entityId)&&this.#R(n.work.entityId);return this.#Z(t,r==="progress"?e.members.map(n=>n.work.entityId):[r.entityId])}if(r==="again")return t.held?.entityId===i&&(t.held=null),!0;if(r.advanced?.length&&this.#Y(t,r.advanced),t.kind==="line"){const n=y(e,r.dependency);if(n!==null)return t.endsBefore=n,!0}return this.#tt(t,e,r,s),t.kind==="lane"&&this.#N(t),t.held.due}#K(t,e,s){if(s.cause!==void 0)return!1;const i=e.members[0].work.entityId,r=s.dependency?.entityIds??[i];return r.length===0||r.some(n=>n!==i)?!1:s.dependency?.producer==="capability"?!0:this.#U(t,e)>=m}#U(t,e){const s=t.held,i=e.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#o.targetOf(e)?s.attempt:0)+1}async#Q(t,e){const s=t.held,i=e.members[0];return!s||i===void 0||s.entityId!==i.work.entityId||s.due||s.notBefore<=this.#t.now()||this.#o.targetOf(e)!==s.target||e.cutoff!==s.cutoff?!1:await this.#t.store.localWorkAfter(e.authorityId,i.work.entityId,s.kept??s.target)===null}#Z(t,e){return t.held&&(t.held.entityId===null||e.includes(t.held.entityId))&&(t.held=null),this.#Y(t,e),!0}#Y(t,e){t.kind==="lane"&&(this.#n=!0,this.#b(t.unit)),this.#c("apply",e);for(const s of this.#w())s!==t&&s.held?.releaseOnProgress&&!s.held.due&&(s.held.due=!0,this.#i(s))}#tt(t,e,s,i){if(s.dependency&&O(s.dependency),s.blocker&&!s.dependency)throw new Error("Apply blocker must name the dependency that releases it");const r=e.members[0].work.entityId,n=t.held,h=this.#U(t,e),l=this.#C(h),o={entityId:r,target:this.#o.targetOf(e),kept:e.members[0].work.kept,cutoff:e.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#t.now()+l,releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#W(s.dependency,s.comparedAt??i):!1,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};t.held=o,this.#$();const A=c(n),f=c(o);f&&JSON.stringify(f)!==JSON.stringify(A)&&this.#t.onWaiting?.(f),!(!s.report&&h<m)&&this.#S(new Error(`${g(t)} holds at ${r}, which ${s.releaseOnProgress?"is parked on a conflict":s.report?"failed":"stands on ground that keeps moving"}, and will retry in ${l}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#j(t,e){if(t.kind==="lane"){for(const h of t.waiters)h.fail(e);t.waiters.clear()}const s=t.held,i=(s?.entityId===null?s.attempt:0)+1,r=this.#C(i),n=e instanceof Error?e.message:String(e);t.held={entityId:null,target:null,kept:null,cutoff:null,attempt:i,notBefore:this.#t.now()+r,releaseOnProgress:!1,due:!1,reason:n},this.#$(),this.#S(new Error(`${g(t)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:e}))}#S(t){try{this.#M(t)}catch{}}#C(t){const e=Math.min(w,M*2**Math.min(t-1,16)),s=Math.max(0,Math.min(1,this.#t.schedule.random()));return Math.round(e*(.5+s))}#c(t,e){const s=++this.#A;for(const i of e??["*"])this.#v.set(`${t}:${i}`,s);for(const i of this.#w())$(i,t,e)&&this.#i(i)}#W(t,e){return["*",...t.entityIds].some(s=>(this.#v.get(`${t.producer}:${s}`)??0)>e)}#$(){if(this.#e)return;let t=this.#p;for(const i of this.#w())i.held&&!i.held.due&&(t=Math.min(t,i.held.notBefore));if(t===1/0){this.#q();return}if(this.#y?.dueAt===t)return;this.#q();const e=Math.max(0,t-this.#t.now()),s=this.#t.schedule.schedule(e,()=>{this.#y=null,this.#z(t),this.#r()});this.#y={dueAt:t,cancel:a(()=>s.cancel(),"cancel")}}#z(t){let e=!1;for(const s of this.#w())s.held&&!s.held.due&&s.held.notBefore<=t&&(s.held.due=!0,this.#i(s),e=!0);return this.#p<=t&&(this.#p=1/0,this.#n=!0,e=!0),e}#q(){this.#y?.cancel(),this.#y=null}}const g=a(d=>d.kind==="line"?`entity Apply line ${d.authorityId}`:`entity Apply fetch of ${d.unit}`,"label");export{q as ENTITY_APPLY_DEFAULT_CONCURRENCY,M as ENTITY_APPLY_RETRY_BASE_MS,w as ENTITY_APPLY_RETRY_MAX_MS,m as ENTITY_APPLY_SAME_ANSWERS,U as EntityApplyRail};
|
|
1
|
+
var k=Object.defineProperty;var a=(d,e)=>k(d,"name",{value:e,configurable:!0});import{UUID_PATTERN as u}from"../entities/types.js";import{FetchAhead as E}from"./fetch-ahead.js";import{EntityApplyJourney as b,outcomeOf as w,stepsAside as P}from"./journey.js";import{assertApplyLaneStep as O,createApplyLane as v}from"./lane.js";import{assertApplyDependency as S,assertApplyLineStep as $,createApplyLine as q,heldWait as c,releaseApplyLine as M}from"./line.js";import{windowEndForWait as g}from"./window.js";const _=8,x=1e3,m=3e4,p=3;class j{static{a(this,"EntityApplyRail")}#e;#g;#P;#M;#_;#o;#O;#a=!1;#t=!1;#d=new Map;#s=new Map;#l={queue:[],steps:new Set};#u={queue:[],steps:new Set};#n=!1;#h=null;#p=1/0;#m=[];#A=0;#v=new Map;#y=null;constructor(e){this.#e=e,this.#g=e.concurrency??_,this.#P=e.laneConcurrency??this.#g,this.#M=e.onBackgroundError??(()=>{}),this.#_=e.onIdle??(()=>{});for(const[t,s]of[["concurrency",this.#g],["lane concurrency",this.#P]])if(!Number.isSafeInteger(s)||s<1)throw new Error(`entity Apply ${t} must be a positive integer`);this.#o=new b(e,()=>this.#A,()=>this.#t),this.#O=new E(e.cargo,{sha256Hex:e.sha256Hex,loops:e.loops})}async start(){if(this.#a)throw new Error("entity Apply rail already started");if(this.#t)throw new Error("entity Apply rail is stopped");this.#a=!0;const e=await this.#e.store.readOpenUnits();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(t=>!u.test(t)))throw new Error("entity Apply store returned an invalid open unit list");for(const t of e)this.#E(t,null);await this.#x()}fetch(e,t){return this.#a?this.#t?Promise.reject(new Error("entity Apply rail is stopped")):u.test(e)?!Number.isFinite(t.stall)||t.stall<0?Promise.reject(new Error("entity Apply fetch needs a non-negative stall")):t.emptied!==void 0&&typeof t.emptied!="boolean"?Promise.reject(new Error("entity Apply fetch emptied must be a boolean")):new Promise((s,i)=>{const r=this.#E(e,null,t.emptied===!0),n=a(()=>this.#e.schedule.schedule(t.stall,()=>{r.waiters.delete(l)&&(r.emptied&&![...r.waiters].some(o=>o.emptied)&&(r.emptied=!1),s(this.#G(r)))}),"arm");let h=n();const l={emptied:t.emptied===!0,answer:a(o=>{h.cancel(),s(o)},"answer"),fail:a(o=>{h.cancel(),i(o)},"fail"),moved:a(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(l),r.waitsOn===null&&this.#N(r),this.#r()}):Promise.reject(new Error("entity Apply fetch needs a unit UUID")):Promise.reject(new Error("entity Apply rail has not started"))}progressed(e,t){if(!u.test(e))throw new Error("entity Apply progress needs a unit UUID");if(!Number.isSafeInteger(t)||t<0)throw new Error("entity Apply progress needs a byte count");t>0&&!this.#t&&this.#b(e)}recordsAvailable(){this.#I()}localStateChanged(e){this.#c("detect",e),this.#c("apply",e),this.#I()}sendAccepted(e){this.#c("send",e),this.#I()}capabilityChanged(e){this.#c("capability",e),this.#I()}owe(e){if(e.some(t=>!u.test(t)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#a||this.#t)){for(const t of e)this.#R(t);this.#r()}}#I(){!this.#a||this.#t||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(e=>c(e.held)??[])}async flush(){if(!this.#a)throw new Error("entity Apply rail has not started");this.#t||await this.#x()}async stop(){if(this.#t)return;this.#t=!0,this.#q();for(const t of[this.#l,this.#u])for(const s of t.queue.splice(0))s.queued=!1;const e=new Error("entity Apply rail stopped before the fetch answered");for(const t of this.#s.values())for(const s of t.waiters)s.fail(e);for(this.#s.clear();this.#B()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#O.stop();for(const t of this.#m.splice(0))t.resolve()}#x(){return new Promise((e,t)=>{this.#m.push({resolve:e,reject:t}),this.#n=!0,this.#r()})}#r(){if(!this.#t){if(this.#n&&this.#h===null){this.#n=!1;const e=this.#F();this.#h=e,e.then(()=>{this.#h=null,this.#r()})}for(const[e,t]of[[this.#u,this.#P],[this.#l,this.#g]])for(;e.steps.size<t&&e.queue.length>0;){const s=e.queue.shift();s.queued=!1,this.#D(s,e)}if(this.#B()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#v.clear(),this.#z(this.#e.now())){this.#r();return}this.#$();for(const e of this.#m.splice(0))e.resolve();this.#_()}}}#B(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#d.values(),...this.#s.values()]}#k(e){return e.kind==="line"?this.#d.get(e.authorityId)===e:this.#s.get(e.unit)===e}#i(e){if(!this.#t){if(e.running){e.again=!0;return}e.queued||(e.queued=!0,(e.kind==="line"?this.#l:this.#u).queue.push(e))}}#D(e,t){e.running=!0,e.again=!1;const s=(e.kind==="line"?this.#J(e):this.#H(e)).then(i=>{e.running=!1,t.steps.delete(s),(i||e.again)&&this.#k(e)&&(e.again=!1,this.#i(e)),this.#r()});t.steps.add(s)}async#F(){try{const e=await this.#e.store.readApplyAuthorities();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(s=>typeof s!="string"||s.length===0))throw new Error("entity Apply store returned an invalid authority list");this.#p=1/0;const t=new Set(e);for(const[s,i]of this.#d)!t.has(s)&&!i.running&&!i.queued&&this.#d.delete(s);for(const s of e){let i=this.#d.get(s);i||(i=q(s),this.#d.set(s,i)),this.#i(i)}}catch(e){this.#p=this.#e.now()+m;const t=this.#m.splice(0);t.length===0&&this.#S(e);for(const s of t)s.reject(e)}}async#J(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#A,i=await this.#e.store.readApplyWindow(e.authorityId,e.endsBefore);if($(e.authorityId,i),this.#t)return!1;if(i.kind==="end"){e.held=null;const r=e.endsBefore!==null;return e.endsBefore=null,r}return i.window.deliverySequence!==null&&this.#O.advance(e.authorityId,i.window.deliverySequence),await this.#L(e,i.window,s)}catch(t){return this.#j(e,t),!1}}async#H(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#A,i=await this.#e.store.readFetchWindow(e.unit,e.toPrefix?null:e.through);if(O(e.unit,i),this.#t||!this.#k(e))return!1;switch((i.kind!=="window"||i.window.intent===null)&&(e.toPrefix=!1),e.through!==null&&i.through>e.through&&e.met.clear(),e.through=Math.max(e.through??0,i.through),e.waitsOn=null,i.kind!=="window"&&(e.held=null),i.kind){case"end":return this.#f(e,{kind:"placed"}),!1;case"nowhere":return this.#f(e,{kind:"nowhere",reason:i.reason}),!1;case"root":return await this.#V(e,i.through,i.reason);case"prerequisite":return this.#X(e,i.unit,i.reason,s);case"window":return await this.#L(e,i.window,s)}}catch(t){return this.#j(e,t),!1}}async#V(e,t,s){return e.met.has(e.unit)?(this.#f(e,{kind:"held",unit:e.unit,reason:`${e.unit} entered and still not held: ${s}`}),!1):(await this.#e.effects.enterRoot(e.unit,t),this.#t||!this.#k(e)?!1:(e.through===t&&e.met.add(e.unit),this.#b(e.unit),!0))}#R(e){const t=this.#E(e,null);t.toPrefix=!0,t.met.clear(),this.#i(t)}#E(e,t,s=!1){let i=this.#s.get(e);return i?t!==null&&(i.through===null||i.through<t)&&(i.through=t,i.met.clear(),this.#i(i)):(i=v(e,t,s),this.#s.set(e,i),this.#i(i)),i}#X(e,t,s,i){if(e.met.has(t))return this.#f(e,{kind:"held",unit:t,reason:`${t} placed and still needed: ${s}`}),!1;if(!this.#T(e,t,s))return!1;const r={producer:"apply",entityIds:[t]};return e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#W(r,i),reason:s,dependency:r},e.held.due}#N(e){const t=e.held;if(t?.dependency?.producer==="apply"){for(const s of t.dependency.entityIds)if(s!==e.unit&&!e.met.has(s)&&!this.#T(e,s,t.reason))return}}#T(e,t,s){const i=[e];let r=this.#s.get(t);for(;r&&r!==e&&!i.includes(r);)i.push(r),r=r.waitsOn===null?void 0:this.#s.get(r.waitsOn);if(r===e){for(const n of i)this.#f(n,{kind:"held",unit:t,reason:`prerequisite cycle through ${t}: ${s}`});return!1}return e.waitsOn??=t,this.#i(this.#E(t,e.through)),!0}#f(e,t){if(!this.#k(e))return;for(const i of e.waiters)i.answer(t);e.waiters.clear(),e.waitsOn=null,(t.kind==="placed"||e.held?.entityId==null)&&this.#s.delete(e.unit);const s=t.kind==="placed"||t.kind==="held"?t:{kind:"held",unit:e.unit,reason:`${e.unit} is nowhere here: ${t.reason}`};for(const i of[...this.#s.values()])if(i.waitsOn===e.unit){if(t.kind!=="placed"){this.#f(i,s);continue}i.met.add(e.unit)}t.kind==="placed"&&(this.#b(e.unit),this.#c("apply",[e.unit]))}#b(e){const t=new Map([[e,!0]]);for(const s of this.#s.values()){const i=new Set;let r=s.unit;for(;r!==null&&!t.has(r)&&!i.has(r);)i.add(r),r=this.#s.get(r)?.waitsOn??null;const n=r!==null&&t.get(r)===!0;for(const h of i)t.set(h,n);if(n)for(const h of s.waiters)h.moved()}}#G(e){let t=e;const s=new Set([e]);for(let i=e.waitsOn===null?void 0:this.#s.get(e.waitsOn);i&&!s.has(i);i=i.waitsOn===null?void 0:this.#s.get(i.waitsOn))s.add(i),t=i;return{kind:"held",unit:t.unit,reason:t.held?.reason??"still placing"}}async#L(e,t,s){const i=t.members[0]?.work.entityId??null;if(e.held&&e.held.entityId!==null&&e.held.entityId!==i&&(e.held=null),await this.#Q(e,t))return!1;let r=await w(()=>this.#o.run(t,()=>e.kind==="lane"&&e.emptied?e.unit:null));if(e.kind==="line"&&typeof r=="object"&&r.kind==="park"&&g(t,r.dependency)===null&&this.#K(e,t,r)&&(r=await w(()=>this.#o.alone(t.members[0]))),r==="progress"||typeof r=="object"&&r.kind==="alone"){if(e.kind==="line")for(const n of t.members)(n.judgment==="waiting"||r!=="progress"&&n.work.entityId===r.entityId)&&this.#R(n.work.entityId);return this.#Z(e,r==="progress"?t.members.map(n=>n.work.entityId):[r.entityId])}if(r==="again")return e.held?.entityId===i&&(e.held=null),!0;if(r.advanced?.length&&this.#Y(e,r.advanced),e.kind==="line"){const n=g(t,r.dependency);if(n!==null)return e.endsBefore=n,!0}return this.#ee(e,t,r,s),e.kind==="lane"&&this.#N(e),e.held.due}#K(e,t,s){const i=t.members[0].work.entityId;if(s.cause!==void 0||!P(t,i))return!1;const r=s.dependency?.entityIds??[i];return r.length===0||r.some(n=>n!==i)?!1:s.dependency?.producer==="capability"?!0:this.#U(e,t)>=p}#U(e,t){const s=e.held,i=t.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#o.targetOf(t)?s.attempt:0)+1}async#Q(e,t){const s=e.held,i=t.members[0];return!s||i===void 0||s.entityId!==i.work.entityId||s.due||s.notBefore<=this.#e.now()||this.#o.targetOf(t)!==s.target||t.cutoff!==s.cutoff?!1:await this.#e.store.localWorkAfter(t.authorityId,i.work.entityId,s.kept??s.target)===null}#Z(e,t){return e.held&&(e.held.entityId===null||t.includes(e.held.entityId))&&(e.held=null),this.#Y(e,t),!0}#Y(e,t){e.kind==="lane"&&(this.#n=!0,this.#b(e.unit)),this.#c("apply",t);for(const s of this.#w())s!==e&&s.held?.releaseOnProgress&&!s.held.due&&(s.held.due=!0,this.#i(s))}#ee(e,t,s,i){if(s.dependency&&S(s.dependency),s.blocker&&!s.dependency)throw new Error("Apply blocker must name the dependency that releases it");const r=t.members[0].work.entityId,n=e.held,h=this.#U(e,t),l=this.#C(h),o=s.again===!0&&h<p,y={entityId:r,target:this.#o.targetOf(t),kept:t.members[0].work.kept,cutoff:t.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#e.now()+(o?0:l),releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#W(s.dependency,s.comparedAt??i):o,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};e.held=y,this.#$();const I=c(n),f=c(y);f&&JSON.stringify(f)!==JSON.stringify(I)&&this.#e.onWaiting?.(f),!(!s.report&&(s.dependency!==void 0||h<p))&&this.#S(new Error(`${A(e)} holds at ${r}, which ${s.releaseOnProgress?"is parked on a conflict":s.report?"failed":s.again?"keeps ending unplaced":"stands on ground that keeps moving"}, and will retry in ${l}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#j(e,t){if(e.kind==="lane"){for(const h of e.waiters)h.fail(t);e.waiters.clear()}const s=e.held,i=(s?.entityId===null?s.attempt:0)+1,r=this.#C(i),n=t instanceof Error?t.message:String(t);e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:i,notBefore:this.#e.now()+r,releaseOnProgress:!1,due:!1,reason:n},this.#$(),this.#S(new Error(`${A(e)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:t}))}#S(e){try{this.#M(e)}catch{}}#C(e){const t=Math.min(m,x*2**Math.min(e-1,16)),s=Math.max(0,Math.min(1,this.#e.schedule.random()));return Math.round(t*(.5+s))}#c(e,t){const s=++this.#A;for(const i of t??["*"])this.#v.set(`${e}:${i}`,s);for(const i of this.#w())M(i,e,t)&&this.#i(i)}#W(e,t){return["*",...e.entityIds].some(s=>(this.#v.get(`${e.producer}:${s}`)??0)>t)}#$(){if(this.#t)return;let e=this.#p;for(const i of this.#w())i.held&&!i.held.due&&(e=Math.min(e,i.held.notBefore));if(e===1/0){this.#q();return}if(this.#y?.dueAt===e)return;this.#q();const t=Math.max(0,e-this.#e.now()),s=this.#e.schedule.schedule(t,()=>{this.#y=null,this.#z(e),this.#r()});this.#y={dueAt:e,cancel:a(()=>s.cancel(),"cancel")}}#z(e){let t=!1;for(const s of this.#w())s.held&&!s.held.due&&s.held.notBefore<=e&&(s.held.due=!0,this.#i(s),t=!0);return this.#p<=e&&(this.#p=1/0,this.#n=!0,t=!0),t}#q(){this.#y?.cancel(),this.#y=null}}const A=a(d=>d.kind==="line"?`entity Apply line ${d.authorityId}`:`entity Apply fetch of ${d.unit}`,"label");export{_ as ENTITY_APPLY_DEFAULT_CONCURRENCY,x as ENTITY_APPLY_RETRY_BASE_MS,m as ENTITY_APPLY_RETRY_MAX_MS,p as ENTITY_APPLY_SAME_ANSWERS,j as EntityApplyRail};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var x=Object.defineProperty;var m=(l,e)=>x(l,"name",{value:e,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.EntityApplyJourney=void 0,exports.stepsAside=q,exports.outcomeOf=D;const _=require("./contracts.js"),j=require("./plans.js"),M=require("../faults/recover.js"),E=require("../faults/classify.js"),P=require("../clash/local-work.js"),O=require("./selection.js"),W=require("./settling.js"),S=require("./window.js");function q(l,e){return l.unit===null&&l.authorityId!==e}m(q,"stepsAside");const F=m(l=>l.kind==="captured-local"||l.kind==="rejudge","drops");function v(l){return l.kind==="retry"?{kind:"park",reason:l.reason??"machine truth is unsettled",releaseOnProgress:!1,report:!1}:l.kind==="dependency"?{kind:"park",reason:l.reason,releaseOnProgress:l.waitFor===void 0,report:!1,...l.waitFor?{dependency:l.waitFor}:{},...l.blocker?{blocker:l.blocker}:{},..."comparedAt"in l?{comparedAt:l.comparedAt}:{}}:l.kind==="conflict"?{kind:"park",reason:l.reason,releaseOnProgress:!0,report:!0}:null}m(v,"parkFor");async function D(l){try{return await l()}catch(e){return{kind:"park",reason:e instanceof Error?e.message:String(e),releaseOnProgress:!1,report:!(0,E.groundMoved)(e),cause:e}}}m(D,"outcomeOf");const I=m(l=>(0,W.isSettlement)(l.judgment)?{kind:"settled",settlement:l.judgment}:null,"settled");class H{static{m(this,"EntityApplyJourney")}#e;#a;#r;#n;constructor(e,t,i){this.#e=e,this.#a={sha256Hex:e.sha256Hex,loops:e.loops},this.#r=t,this.#n=i}targetOf(e){const t=e.members[0];return t===void 0?null:e.intent?.members.find(i=>i.entityId===t.work.entityId)?.throughSequence??(t.work.kept===null?t.work.records.at(-1)?.globalSequence:t.work.resolvedThrough)??null}async run(e,t){if(e.intent!==null)return this.#p(e,e.intent);const i={member:null};try{return await this.#d(e,t,i)}catch(a){if(i.member===null||this.#n())throw a;if((0,E.groundMoved)(a))return{kind:"park",reason:a instanceof Error?a.message:String(a),releaseOnProgress:!1,report:!1};if(q(e,i.member.work.entityId))return this.alone(i.member);if(a instanceof M.Recovering)return{kind:"park",reason:a.message,releaseOnProgress:!1,report:!1,dependency:{producer:"capability",entityIds:a.need.subject===null?[]:[a.need.subject.id]}};throw a}}async alone(e){const t=await this.#t(null,[e],[{kind:"settled",settlement:"waiting"}]);return t==="progress"?{kind:"alone",entityId:e.work.entityId}:t}async#d(e,t,i){const a=this.#e.newIntentId(),n=this.#e.now(),o=t(),s=new Map;for(const c of e.members){if(I(c))continue;const{work:f}=c,w=(0,O.selectEntityApply)(f,this.#a),b=(0,_.createApplyIntent)({attemptId:a,work:f,target:w.target,unit:e.unit,cutoff:e.cutoff,createdAt:n,emptied:f.entityId===o&&f.play==="enter"&&(w.target.result.type==="file.text"||w.target.result.type==="file.binary")}),h=(0,j.planSelectedEntityApply)(f,w,this.#e.sha256Hex);s.set(f.entityId,{member:c,intent:b,plan:h,adapter:this.#e.effects.adapterFor(h.target.type),look:"safe"})}const{active:d,blocked:y}=await this.#o(e.members,s,"look",i);if(d.length===0)return y??"again";const g=d.flatMap(c=>s.get(c.work.entityId)??[]);if(g.length===0)return this.#t(null,d,d.map(c=>I(c)));const k=(0,_.createApplyWindowIntent)({attemptId:a,authorityId:e.authorityId,unit:e.unit,cutoff:e.cutoff,createdAt:n,members:g.map(c=>c.intent)});try{const c=await this.#u(d,s,i),f=c.active.flatMap(r=>s.get(r.work.entityId)??[]);if(f.length===0)return await this.#e.effects.discard(k),c.active.length===0?c.blocked??"again":this.#t(null,c.active,c.active.map(r=>I(r)));const w=f.length===g.length?k:(0,_.createApplyWindowIntent)({...k,members:f.map(r=>r.intent)}),b=await this.#e.effects.hold(w,f.map(r=>r.plan));let h,A;try{h=await this.#o(c.active,s,"final",i),A=await this.#c(w,h,s,t)}finally{b()}return h.unseen!==null&&h.active.length===0?this.#y(h.unseen):A}catch(c){throw await this.#e.effects.discard(k),c}}async#c(e,{active:t,blocked:i},a,n){const o=t.flatMap(r=>a.get(r.work.entityId)??[]);if(o.length===0)return await this.#e.effects.discard(e),t.length===0?i??"again":this.#t(null,t,t.map(r=>I(r)));const s=(0,_.createApplyWindowIntent)({...e,members:o.map(r=>r.intent)}),d=o.filter(r=>r.look==="safe");if(d.length>0){if(this.#n()||o.some(p=>p.intent.emptied&&n()!==p.intent.entityId))return await this.#e.effects.discard(e),"again";const r=await this.#e.store.bindWindow(s);if(r)return await this.#e.effects.discard(e),r.kind==="stale"?"again":v({...r,comparedAt:this.#r()})}const y=new Map,g=new Map,k=m((r,p,u=null)=>{y.set(r,{kind:"owed",reason:p}),u!==null&&g.set(r,u)},"owe"),c=m(r=>v(r.kind==="dependency"?{...r,comparedAt:this.#r()}:r),"waitFrom"),{order:f,cycle:w}=(0,S.revealOrder)(d.map(r=>({entityId:r.intent.entityId,play:r.plan.play,type:r.plan.target.type,parentUUID:r.plan.target.parentUUID}))),b="its parent chain closes among the window's members";for(const r of w)k(r,b,{kind:"park",reason:b,releaseOnProgress:!1,report:!0});for(const r of f){const p=a.get(r),u=await p.adapter.apply.reveal(p.intent,p.plan);u&&k(r,u.reason,u.kind==="dependency"?c(u):null)}for(const r of o){const p=r.intent.entityId;if(y.has(p))continue;const u=await r.adapter.verify.verify(r.intent,r.plan);u.kind==="match"?y.set(p,{kind:"materialized"}):u.kind==="local-change"?k(p,"a person's version stands in its place"):u.kind==="rejudge"||u.kind==="missing-target"?k(p,u.kind):k(p,u.reason??u.kind,c(u))}const h=t.map(r=>I(r)??y.get(r.work.entityId));if(d.length>0)return this.#s(s,t,h,g);const A=await this.#s(null,t,h,g);return await this.#e.effects.discard(e),A}async#s(e,t,i,a){const n=await this.#t(e,t,i),o=i[0];return n!=="progress"||o.kind!=="owed"?n:{...a.get(t[0].work.entityId)??{kind:"park",reason:o.reason,releaseOnProgress:!1,report:!1,again:!0},advanced:t.filter((d,y)=>i[y].kind!=="owed").map(d=>d.work.entityId)}}async#o(e,t,i,a){const n=[];for(const o of e){const s=t.get(o.work.entityId);if(!s){n.push(o);continue}let d;try{d=await this.#i(s.intent)?{kind:"captured-local"}:i==="look"?await this.#f(s):await s.adapter.apply.guard(s.intent,s.plan,i)}catch(g){if(n.length>0&&!this.#n())return{active:n,blocked:null,unseen:null};throw a.member=o,g}if(d.kind==="local-change"||d.kind==="unsettled-ground")return{active:n,blocked:n.length===0?"again":null,unseen:s};if(F(d))return{active:n,blocked:n.length===0?"again":null,unseen:null};const y=v(d);if(y)return{active:n,blocked:y,unseen:null};s.look=d.kind,n.push(o)}return{active:n,blocked:null,unseen:null}}async#u(e,t,i){for(const[a,n]of e.entries()){const o=t.get(n.work.entityId);if(!(!o||o.look!=="safe"))try{const s=await o.adapter.apply.prepare(o.intent,o.plan);if(s)return{active:e.slice(0,a),blocked:v(s)}}catch(s){if(a>0&&!this.#n())return{active:e.slice(0,a),blocked:null};throw i.member=n,s}}return{active:[...e],blocked:null}}async#p(e,t){const i=t.members.map(n=>{const o=e.members.find(d=>d.work.entityId===n.entityId);if(!o)return null;const s=n.kept===null?o.work:{...o.work,records:[],kept:n.kept};return s.records.length===0&&s.kept===null?null:(0,j.planSelectedEntityApply)(s,(0,O.selectEntityApply)(s,this.#a,n),this.#e.sha256Hex)}),a=await this.#e.effects.recover(t,i);if(a.length!==t.members.length)throw new Error("Apply recovery answered for a different window");return this.#t(t,e.members,e.members.map(n=>I(n)??a[t.members.findIndex(o=>o.entityId===n.work.entityId)]??{kind:"owed",reason:"not a member of the bound window"}))}async#t(e,t,i){const a=await this.#e.store.endWindow(e,t,i);if(!a)return"progress";if(a.kind!=="stale"||!a.reason)throw new Error("Apply end commit returned an unknown refusal");return"again"}async#i(e){return(0,P.localWorkWins)(e.targetType,await this.#e.store.localWorkAfter(e.authorityId,e.entityId,e.kept??e.throughSequence))}async#f(e){const{intent:t,plan:i,adapter:a}=e,n=await a.apply.guard(t,i,"look");if(n.kind!=="local-change"&&n.kind!=="unsettled-ground")return n;const o=await this.#l(t,i);if(o.kind!=="observed")return o;const s=await a.apply.guard(t,i,"look");return s.kind==="local-change"||s.kind==="unsettled-ground"?{kind:"retry",reason:"Ground still needs observation after Detect; this member cannot reveal."}:s}async#y(e){const t=await this.#l(e.intent,e.plan);return t.kind==="captured-local"?"again":v(t.kind==="observed"?{kind:"retry",reason:"Its final guard found ground Detect had not recorded; it is judged again after Detect looks."}:t)}async#l(e,t){if(await this.#i(e))return{kind:"captured-local"};let i,a=!0;const n=await this.#e.effects.captureLocal(e,t,()=>{if(!a||i!==void 0)throw new Error("Apply capture comparison must be marked exactly once");i=this.#r()}).finally(()=>{a=!1});if(!n||!["settled","local-only","retry"].includes(n.kind))throw new Error("Apply capture returned no explicit observation outcome");if(await this.#i(e))return{kind:"captured-local"};if(n.kind==="retry")return n;if(n.kind==="local-only"){if(i===void 0)throw new Error("local-only capture requires a synchronous comparison fence");if(!n.reason||n.entityIds.length===0||n.entityIds.some(o=>!o))throw new Error("local-only capture must name the retained ground and its releasing condition");return{kind:"dependency",reason:n.reason,comparedAt:i,waitFor:{producer:"detect",entityIds:n.entityIds}}}return{kind:"observed"}}}exports.EntityApplyJourney=H;
|
package/dist-cjs/apply/rail.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var m=Object.defineProperty;var d=(l,e)=>m(l,"name",{value:e,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.EntityApplyRail=exports.ENTITY_APPLY_SAME_ANSWERS=exports.ENTITY_APPLY_RETRY_MAX_MS=exports.ENTITY_APPLY_RETRY_BASE_MS=exports.ENTITY_APPLY_DEFAULT_CONCURRENCY=void 0;const f=require("../entities/types.js"),_=require("./fetch-ahead.js"),p=require("./journey.js"),y=require("./lane.js"),o=require("./line.js"),w=require("./window.js");exports.ENTITY_APPLY_DEFAULT_CONCURRENCY=8,exports.ENTITY_APPLY_RETRY_BASE_MS=1e3,exports.ENTITY_APPLY_RETRY_MAX_MS=3e4,exports.ENTITY_APPLY_SAME_ANSWERS=3;class E{static{d(this,"EntityApplyRail")}#e;#g;#k;#N;#O;#a;#T;#d=!1;#t=!1;#o=new Map;#s=new Map;#l={queue:[],steps:new Set};#u={queue:[],steps:new Set};#n=!1;#h=null;#p=1/0;#A=[];#m=0;#S=new Map;#y=null;constructor(e){this.#e=e,this.#g=e.concurrency??exports.ENTITY_APPLY_DEFAULT_CONCURRENCY,this.#k=e.laneConcurrency??this.#g,this.#N=e.onBackgroundError??(()=>{}),this.#O=e.onIdle??(()=>{});for(const[t,s]of[["concurrency",this.#g],["lane concurrency",this.#k]])if(!Number.isSafeInteger(s)||s<1)throw new Error(`entity Apply ${t} must be a positive integer`);this.#a=new p.EntityApplyJourney(e,()=>this.#m,()=>this.#t),this.#T=new _.FetchAhead(e.cargo,{sha256Hex:e.sha256Hex,loops:e.loops})}async start(){if(this.#d)throw new Error("entity Apply rail already started");if(this.#t)throw new Error("entity Apply rail is stopped");this.#d=!0;const e=await this.#e.store.readOpenUnits();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(t=>!f.UUID_PATTERN.test(t)))throw new Error("entity Apply store returned an invalid open unit list");for(const t of e)this.#I(t,null);await this.#M()}fetch(e,t){return this.#d?this.#t?Promise.reject(new Error("entity Apply rail is stopped")):f.UUID_PATTERN.test(e)?!Number.isFinite(t.stall)||t.stall<0?Promise.reject(new Error("entity Apply fetch needs a non-negative stall")):t.emptied!==void 0&&typeof t.emptied!="boolean"?Promise.reject(new Error("entity Apply fetch emptied must be a boolean")):new Promise((s,i)=>{const r=this.#I(e,null,t.emptied===!0),n=d(()=>this.#e.schedule.schedule(t.stall,()=>{r.waiters.delete(u)&&(r.emptied&&![...r.waiters].some(a=>a.emptied)&&(r.emptied=!1),s(this.#G(r)))}),"arm");let h=n();const u={emptied:t.emptied===!0,answer:d(a=>{h.cancel(),s(a)},"answer"),fail:d(a=>{h.cancel(),i(a)},"fail"),moved:d(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(u),r.waitsOn===null&&this.#$(r),this.#r()}):Promise.reject(new Error("entity Apply fetch needs a unit UUID")):Promise.reject(new Error("entity Apply rail has not started"))}progressed(e,t){if(!f.UUID_PATTERN.test(e))throw new Error("entity Apply progress needs a unit UUID");if(!Number.isSafeInteger(t)||t<0)throw new Error("entity Apply progress needs a byte count");t>0&&!this.#t&&this.#P(e)}recordsAvailable(){this.#_()}localStateChanged(e){this.#c("detect",e),this.#c("apply",e),this.#_()}sendAccepted(e){this.#c("send",e),this.#_()}capabilityChanged(e){this.#c("capability",e),this.#_()}owe(e){if(e.some(t=>!f.UUID_PATTERN.test(t)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#d||this.#t)){for(const t of e)this.#q(t);this.#r()}}#_(){!this.#d||this.#t||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(e=>(0,o.heldWait)(e.held)??[])}async flush(){if(!this.#d)throw new Error("entity Apply rail has not started");this.#t||await this.#M()}async stop(){if(this.#t)return;this.#t=!0,this.#b();for(const t of[this.#l,this.#u])for(const s of t.queue.splice(0))s.queued=!1;const e=new Error("entity Apply rail stopped before the fetch answered");for(const t of this.#s.values())for(const s of t.waiters)s.fail(e);for(this.#s.clear();this.#v()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#T.stop();for(const t of this.#A.splice(0))t.resolve()}#M(){return new Promise((e,t)=>{this.#A.push({resolve:e,reject:t}),this.#n=!0,this.#r()})}#r(){if(!this.#t){if(this.#n&&this.#h===null){this.#n=!1;const e=this.#z();this.#h=e,e.then(()=>{this.#h=null,this.#r()})}for(const[e,t]of[[this.#u,this.#k],[this.#l,this.#g]])for(;e.steps.size<t&&e.queue.length>0;){const s=e.queue.shift();s.queued=!1,this.#F(s,e)}if(this.#v()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#S.clear(),this.#x(this.#e.now())){this.#r();return}this.#R();for(const e of this.#A.splice(0))e.resolve();this.#O()}}}#v(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#o.values(),...this.#s.values()]}#E(e){return e.kind==="line"?this.#o.get(e.authorityId)===e:this.#s.get(e.unit)===e}#i(e){if(!this.#t){if(e.running){e.again=!0;return}e.queued||(e.queued=!0,(e.kind==="line"?this.#l:this.#u).queue.push(e))}}#F(e,t){e.running=!0,e.again=!1;const s=(e.kind==="line"?this.#X(e):this.#J(e)).then(i=>{e.running=!1,t.steps.delete(s),(i||e.again)&&this.#E(e)&&(e.again=!1,this.#i(e)),this.#r()});t.steps.add(s)}async#z(){try{const e=await this.#e.store.readApplyAuthorities();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(s=>typeof s!="string"||s.length===0))throw new Error("entity Apply store returned an invalid authority list");this.#p=1/0;const t=new Set(e);for(const[s,i]of this.#o)!t.has(s)&&!i.running&&!i.queued&&this.#o.delete(s);for(const s of e){let i=this.#o.get(s);i||(i=(0,o.createApplyLine)(s),this.#o.set(s,i)),this.#i(i)}}catch(e){this.#p=this.#e.now()+exports.ENTITY_APPLY_RETRY_MAX_MS;const t=this.#A.splice(0);t.length===0&&this.#Y(e);for(const s of t)s.reject(e)}}async#X(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#m,i=await this.#e.store.readApplyWindow(e.authorityId,e.endsBefore);if((0,o.assertApplyLineStep)(e.authorityId,i),this.#t)return!1;if(i.kind==="end"){e.held=null;const r=e.endsBefore!==null;return e.endsBefore=null,r}return i.window.deliverySequence!==null&&this.#T.advance(e.authorityId,i.window.deliverySequence),await this.#U(e,i.window,s)}catch(t){return this.#C(e,t),!1}}async#J(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#m,i=await this.#e.store.readFetchWindow(e.unit,e.toPrefix?null:e.through);if((0,y.assertApplyLaneStep)(e.unit,i),this.#t||!this.#E(e))return!1;switch((i.kind!=="window"||i.window.intent===null)&&(e.toPrefix=!1),e.through!==null&&i.through>e.through&&e.met.clear(),e.through=Math.max(e.through??0,i.through),e.waitsOn=null,i.kind!=="window"&&(e.held=null),i.kind){case"end":return this.#f(e,{kind:"placed"}),!1;case"nowhere":return this.#f(e,{kind:"nowhere",reason:i.reason}),!1;case"root":return await this.#H(e,i.through,i.reason);case"prerequisite":return this.#V(e,i.unit,i.reason,s);case"window":return await this.#U(e,i.window,s)}}catch(t){return this.#C(e,t),!1}}async#H(e,t,s){return e.met.has(e.unit)?(this.#f(e,{kind:"held",unit:e.unit,reason:`${e.unit} entered and still not held: ${s}`}),!1):(await this.#e.effects.enterRoot(e.unit,t),this.#t||!this.#E(e)?!1:(e.through===t&&e.met.add(e.unit),this.#P(e.unit),!0))}#q(e){const t=this.#I(e,null);t.toPrefix=!0,t.met.clear(),this.#i(t)}#I(e,t,s=!1){let i=this.#s.get(e);return i?t!==null&&(i.through===null||i.through<t)&&(i.through=t,i.met.clear(),this.#i(i)):(i=(0,y.createApplyLane)(e,t,s),this.#s.set(e,i),this.#i(i)),i}#V(e,t,s,i){if(e.met.has(t))return this.#f(e,{kind:"held",unit:t,reason:`${t} placed and still needed: ${s}`}),!1;if(!this.#L(e,t,s))return!1;const r={producer:"apply",entityIds:[t]};return e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#D(r,i),reason:s,dependency:r},e.held.due}#$(e){const t=e.held;if(t?.dependency?.producer==="apply"){for(const s of t.dependency.entityIds)if(s!==e.unit&&!e.met.has(s)&&!this.#L(e,s,t.reason))return}}#L(e,t,s){const i=[e];let r=this.#s.get(t);for(;r&&r!==e&&!i.includes(r);)i.push(r),r=r.waitsOn===null?void 0:this.#s.get(r.waitsOn);if(r===e){for(const n of i)this.#f(n,{kind:"held",unit:t,reason:`prerequisite cycle through ${t}: ${s}`});return!1}return e.waitsOn??=t,this.#i(this.#I(t,e.through)),!0}#f(e,t){if(!this.#E(e))return;for(const i of e.waiters)i.answer(t);e.waiters.clear(),e.waitsOn=null,(t.kind==="placed"||e.held?.entityId==null)&&this.#s.delete(e.unit);const s=t.kind==="placed"||t.kind==="held"?t:{kind:"held",unit:e.unit,reason:`${e.unit} is nowhere here: ${t.reason}`};for(const i of[...this.#s.values()])if(i.waitsOn===e.unit){if(t.kind!=="placed"){this.#f(i,s);continue}i.met.add(e.unit)}t.kind==="placed"&&(this.#P(e.unit),this.#c("apply",[e.unit]))}#P(e){const t=new Map([[e,!0]]);for(const s of this.#s.values()){const i=new Set;let r=s.unit;for(;r!==null&&!t.has(r)&&!i.has(r);)i.add(r),r=this.#s.get(r)?.waitsOn??null;const n=r!==null&&t.get(r)===!0;for(const h of i)t.set(h,n);if(n)for(const h of s.waiters)h.moved()}}#G(e){let t=e;const s=new Set([e]);for(let i=e.waitsOn===null?void 0:this.#s.get(e.waitsOn);i&&!s.has(i);i=i.waitsOn===null?void 0:this.#s.get(i.waitsOn))s.add(i),t=i;return{kind:"held",unit:t.unit,reason:t.held?.reason??"still placing"}}async#U(e,t,s){const i=t.members[0]?.work.entityId??null;if(e.held&&e.held.entityId!==null&&e.held.entityId!==i&&(e.held=null),await this.#Q(e,t))return!1;let r=await(0,p.outcomeOf)(()=>this.#a.run(t,()=>e.kind==="lane"&&e.emptied?e.unit:null));if(e.kind==="line"&&typeof r=="object"&&r.kind==="park"&&(0,w.windowEndForWait)(t,r.dependency)===null&&this.#K(e,t,r)&&(r=await(0,p.outcomeOf)(()=>this.#a.alone(t.members[0]))),r==="progress"||typeof r=="object"&&r.kind==="alone"){if(e.kind==="line")for(const n of t.members)(n.judgment==="waiting"||r!=="progress"&&n.work.entityId===r.entityId)&&this.#q(n.work.entityId);return this.#Z(e,r==="progress"?t.members.map(n=>n.work.entityId):[r.entityId])}if(r==="again")return e.held?.entityId===i&&(e.held=null),!0;if(r.advanced?.length&&this.#B(e,r.advanced),e.kind==="line"){const n=(0,w.windowEndForWait)(t,r.dependency);if(n!==null)return e.endsBefore=n,!0}return this.#ee(e,t,r,s),e.kind==="lane"&&this.#$(e),e.held.due}#K(e,t,s){if(s.cause!==void 0)return!1;const i=t.members[0].work.entityId,r=s.dependency?.entityIds??[i];return r.length===0||r.some(n=>n!==i)?!1:s.dependency?.producer==="capability"?!0:this.#j(e,t)>=exports.ENTITY_APPLY_SAME_ANSWERS}#j(e,t){const s=e.held,i=t.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#a.targetOf(t)?s.attempt:0)+1}async#Q(e,t){const s=e.held,i=t.members[0];return!s||i===void 0||s.entityId!==i.work.entityId||s.due||s.notBefore<=this.#e.now()||this.#a.targetOf(t)!==s.target||t.cutoff!==s.cutoff?!1:await this.#e.store.localWorkAfter(t.authorityId,i.work.entityId,s.kept??s.target)===null}#Z(e,t){return e.held&&(e.held.entityId===null||t.includes(e.held.entityId))&&(e.held=null),this.#B(e,t),!0}#B(e,t){e.kind==="lane"&&(this.#n=!0,this.#P(e.unit)),this.#c("apply",t);for(const s of this.#w())s!==e&&s.held?.releaseOnProgress&&!s.held.due&&(s.held.due=!0,this.#i(s))}#ee(e,t,s,i){if(s.dependency&&(0,o.assertApplyDependency)(s.dependency),s.blocker&&!s.dependency)throw new Error("Apply blocker must name the dependency that releases it");const r=t.members[0].work.entityId,n=e.held,h=this.#j(e,t),u=this.#W(h),a={entityId:r,target:this.#a.targetOf(t),kept:t.members[0].work.kept,cutoff:t.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#e.now()+u,releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#D(s.dependency,s.comparedAt??i):!1,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};e.held=a,this.#R();const A=(0,o.heldWait)(n),c=(0,o.heldWait)(a);c&&JSON.stringify(c)!==JSON.stringify(A)&&this.#e.onWaiting?.(c),!(!s.report&&h<exports.ENTITY_APPLY_SAME_ANSWERS)&&this.#Y(new Error(`${g(e)} holds at ${r}, which ${s.releaseOnProgress?"is parked on a conflict":s.report?"failed":"stands on ground that keeps moving"}, and will retry in ${u}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#C(e,t){if(e.kind==="lane"){for(const h of e.waiters)h.fail(t);e.waiters.clear()}const s=e.held,i=(s?.entityId===null?s.attempt:0)+1,r=this.#W(i),n=t instanceof Error?t.message:String(t);e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:i,notBefore:this.#e.now()+r,releaseOnProgress:!1,due:!1,reason:n},this.#R(),this.#Y(new Error(`${g(e)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:t}))}#Y(e){try{this.#N(e)}catch{}}#W(e){const t=Math.min(exports.ENTITY_APPLY_RETRY_MAX_MS,exports.ENTITY_APPLY_RETRY_BASE_MS*2**Math.min(e-1,16)),s=Math.max(0,Math.min(1,this.#e.schedule.random()));return Math.round(t*(.5+s))}#c(e,t){const s=++this.#m;for(const i of t??["*"])this.#S.set(`${e}:${i}`,s);for(const i of this.#w())(0,o.releaseApplyLine)(i,e,t)&&this.#i(i)}#D(e,t){return["*",...e.entityIds].some(s=>(this.#S.get(`${e.producer}:${s}`)??0)>t)}#R(){if(this.#t)return;let e=this.#p;for(const i of this.#w())i.held&&!i.held.due&&(e=Math.min(e,i.held.notBefore));if(e===1/0){this.#b();return}if(this.#y?.dueAt===e)return;this.#b();const t=Math.max(0,e-this.#e.now()),s=this.#e.schedule.schedule(t,()=>{this.#y=null,this.#x(e),this.#r()});this.#y={dueAt:e,cancel:d(()=>s.cancel(),"cancel")}}#x(e){let t=!1;for(const s of this.#w())s.held&&!s.held.due&&s.held.notBefore<=e&&(s.held.due=!0,this.#i(s),t=!0);return this.#p<=e&&(this.#p=1/0,this.#n=!0,t=!0),t}#b(){this.#y?.cancel(),this.#y=null}}exports.EntityApplyRail=E;const g=d(l=>l.kind==="line"?`entity Apply line ${l.authorityId}`:`entity Apply fetch of ${l.unit}`,"label");
|
|
1
|
+
"use strict";var _=Object.defineProperty;var d=(l,e)=>_(l,"name",{value:e,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.EntityApplyRail=exports.ENTITY_APPLY_SAME_ANSWERS=exports.ENTITY_APPLY_RETRY_MAX_MS=exports.ENTITY_APPLY_RETRY_BASE_MS=exports.ENTITY_APPLY_DEFAULT_CONCURRENCY=void 0;const f=require("../entities/types.js"),E=require("./fetch-ahead.js"),c=require("./journey.js"),w=require("./lane.js"),o=require("./line.js"),A=require("./window.js");exports.ENTITY_APPLY_DEFAULT_CONCURRENCY=8,exports.ENTITY_APPLY_RETRY_BASE_MS=1e3,exports.ENTITY_APPLY_RETRY_MAX_MS=3e4,exports.ENTITY_APPLY_SAME_ANSWERS=3;class I{static{d(this,"EntityApplyRail")}#e;#A;#k;#b;#O;#a;#T;#d=!1;#t=!1;#o=new Map;#s=new Map;#l={queue:[],steps:new Set};#u={queue:[],steps:new Set};#r=!1;#h=null;#p=1/0;#g=[];#m=0;#S=new Map;#y=null;constructor(e){this.#e=e,this.#A=e.concurrency??exports.ENTITY_APPLY_DEFAULT_CONCURRENCY,this.#k=e.laneConcurrency??this.#A,this.#b=e.onBackgroundError??(()=>{}),this.#O=e.onIdle??(()=>{});for(const[t,s]of[["concurrency",this.#A],["lane concurrency",this.#k]])if(!Number.isSafeInteger(s)||s<1)throw new Error(`entity Apply ${t} must be a positive integer`);this.#a=new c.EntityApplyJourney(e,()=>this.#m,()=>this.#t),this.#T=new E.FetchAhead(e.cargo,{sha256Hex:e.sha256Hex,loops:e.loops})}async start(){if(this.#d)throw new Error("entity Apply rail already started");if(this.#t)throw new Error("entity Apply rail is stopped");this.#d=!0;const e=await this.#e.store.readOpenUnits();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(t=>!f.UUID_PATTERN.test(t)))throw new Error("entity Apply store returned an invalid open unit list");for(const t of e)this.#I(t,null);await this.#M()}fetch(e,t){return this.#d?this.#t?Promise.reject(new Error("entity Apply rail is stopped")):f.UUID_PATTERN.test(e)?!Number.isFinite(t.stall)||t.stall<0?Promise.reject(new Error("entity Apply fetch needs a non-negative stall")):t.emptied!==void 0&&typeof t.emptied!="boolean"?Promise.reject(new Error("entity Apply fetch emptied must be a boolean")):new Promise((s,i)=>{const n=this.#I(e,null,t.emptied===!0),r=d(()=>this.#e.schedule.schedule(t.stall,()=>{n.waiters.delete(u)&&(n.emptied&&![...n.waiters].some(a=>a.emptied)&&(n.emptied=!1),s(this.#G(n)))}),"arm");let h=r();const u={emptied:t.emptied===!0,answer:d(a=>{h.cancel(),s(a)},"answer"),fail:d(a=>{h.cancel(),i(a)},"fail"),moved:d(()=>{h.cancel(),h=r()},"moved")};n.waiters.add(u),n.waitsOn===null&&this.#L(n),this.#n()}):Promise.reject(new Error("entity Apply fetch needs a unit UUID")):Promise.reject(new Error("entity Apply rail has not started"))}progressed(e,t){if(!f.UUID_PATTERN.test(e))throw new Error("entity Apply progress needs a unit UUID");if(!Number.isSafeInteger(t)||t<0)throw new Error("entity Apply progress needs a byte count");t>0&&!this.#t&&this.#P(e)}recordsAvailable(){this.#_()}localStateChanged(e){this.#c("detect",e),this.#c("apply",e),this.#_()}sendAccepted(e){this.#c("send",e),this.#_()}capabilityChanged(e){this.#c("capability",e),this.#_()}owe(e){if(e.some(t=>!f.UUID_PATTERN.test(t)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#d||this.#t)){for(const t of e)this.#q(t);this.#n()}}#_(){!this.#d||this.#t||(this.#r=!0,this.#n())}waiting(){return this.#w().flatMap(e=>(0,o.heldWait)(e.held)??[])}async flush(){if(!this.#d)throw new Error("entity Apply rail has not started");this.#t||await this.#M()}async stop(){if(this.#t)return;this.#t=!0,this.#N();for(const t of[this.#l,this.#u])for(const s of t.queue.splice(0))s.queued=!1;const e=new Error("entity Apply rail stopped before the fetch answered");for(const t of this.#s.values())for(const s of t.waiters)s.fail(e);for(this.#s.clear();this.#v()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#T.stop();for(const t of this.#g.splice(0))t.resolve()}#M(){return new Promise((e,t)=>{this.#g.push({resolve:e,reject:t}),this.#r=!0,this.#n()})}#n(){if(!this.#t){if(this.#r&&this.#h===null){this.#r=!1;const e=this.#z();this.#h=e,e.then(()=>{this.#h=null,this.#n()})}for(const[e,t]of[[this.#u,this.#k],[this.#l,this.#A]])for(;e.steps.size<t&&e.queue.length>0;){const s=e.queue.shift();s.queued=!1,this.#F(s,e)}if(this.#v()===0&&this.#h===null&&!this.#r&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#S.clear(),this.#x(this.#e.now())){this.#n();return}this.#R();for(const e of this.#g.splice(0))e.resolve();this.#O()}}}#v(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#o.values(),...this.#s.values()]}#E(e){return e.kind==="line"?this.#o.get(e.authorityId)===e:this.#s.get(e.unit)===e}#i(e){if(!this.#t){if(e.running){e.again=!0;return}e.queued||(e.queued=!0,(e.kind==="line"?this.#l:this.#u).queue.push(e))}}#F(e,t){e.running=!0,e.again=!1;const s=(e.kind==="line"?this.#X(e):this.#J(e)).then(i=>{e.running=!1,t.steps.delete(s),(i||e.again)&&this.#E(e)&&(e.again=!1,this.#i(e)),this.#n()});t.steps.add(s)}async#z(){try{const e=await this.#e.store.readApplyAuthorities();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(s=>typeof s!="string"||s.length===0))throw new Error("entity Apply store returned an invalid authority list");this.#p=1/0;const t=new Set(e);for(const[s,i]of this.#o)!t.has(s)&&!i.running&&!i.queued&&this.#o.delete(s);for(const s of e){let i=this.#o.get(s);i||(i=(0,o.createApplyLine)(s),this.#o.set(s,i)),this.#i(i)}}catch(e){this.#p=this.#e.now()+exports.ENTITY_APPLY_RETRY_MAX_MS;const t=this.#g.splice(0);t.length===0&&this.#Y(e);for(const s of t)s.reject(e)}}async#X(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#m,i=await this.#e.store.readApplyWindow(e.authorityId,e.endsBefore);if((0,o.assertApplyLineStep)(e.authorityId,i),this.#t)return!1;if(i.kind==="end"){e.held=null;const n=e.endsBefore!==null;return e.endsBefore=null,n}return i.window.deliverySequence!==null&&this.#T.advance(e.authorityId,i.window.deliverySequence),await this.#U(e,i.window,s)}catch(t){return this.#W(e,t),!1}}async#J(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#m,i=await this.#e.store.readFetchWindow(e.unit,e.toPrefix?null:e.through);if((0,w.assertApplyLaneStep)(e.unit,i),this.#t||!this.#E(e))return!1;switch((i.kind!=="window"||i.window.intent===null)&&(e.toPrefix=!1),e.through!==null&&i.through>e.through&&e.met.clear(),e.through=Math.max(e.through??0,i.through),e.waitsOn=null,i.kind!=="window"&&(e.held=null),i.kind){case"end":return this.#f(e,{kind:"placed"}),!1;case"nowhere":return this.#f(e,{kind:"nowhere",reason:i.reason}),!1;case"root":return await this.#H(e,i.through,i.reason);case"prerequisite":return this.#V(e,i.unit,i.reason,s);case"window":return await this.#U(e,i.window,s)}}catch(t){return this.#W(e,t),!1}}async#H(e,t,s){return e.met.has(e.unit)?(this.#f(e,{kind:"held",unit:e.unit,reason:`${e.unit} entered and still not held: ${s}`}),!1):(await this.#e.effects.enterRoot(e.unit,t),this.#t||!this.#E(e)?!1:(e.through===t&&e.met.add(e.unit),this.#P(e.unit),!0))}#q(e){const t=this.#I(e,null);t.toPrefix=!0,t.met.clear(),this.#i(t)}#I(e,t,s=!1){let i=this.#s.get(e);return i?t!==null&&(i.through===null||i.through<t)&&(i.through=t,i.met.clear(),this.#i(i)):(i=(0,w.createApplyLane)(e,t,s),this.#s.set(e,i),this.#i(i)),i}#V(e,t,s,i){if(e.met.has(t))return this.#f(e,{kind:"held",unit:t,reason:`${t} placed and still needed: ${s}`}),!1;if(!this.#$(e,t,s))return!1;const n={producer:"apply",entityIds:[t]};return e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#D(n,i),reason:s,dependency:n},e.held.due}#L(e){const t=e.held;if(t?.dependency?.producer==="apply"){for(const s of t.dependency.entityIds)if(s!==e.unit&&!e.met.has(s)&&!this.#$(e,s,t.reason))return}}#$(e,t,s){const i=[e];let n=this.#s.get(t);for(;n&&n!==e&&!i.includes(n);)i.push(n),n=n.waitsOn===null?void 0:this.#s.get(n.waitsOn);if(n===e){for(const r of i)this.#f(r,{kind:"held",unit:t,reason:`prerequisite cycle through ${t}: ${s}`});return!1}return e.waitsOn??=t,this.#i(this.#I(t,e.through)),!0}#f(e,t){if(!this.#E(e))return;for(const i of e.waiters)i.answer(t);e.waiters.clear(),e.waitsOn=null,(t.kind==="placed"||e.held?.entityId==null)&&this.#s.delete(e.unit);const s=t.kind==="placed"||t.kind==="held"?t:{kind:"held",unit:e.unit,reason:`${e.unit} is nowhere here: ${t.reason}`};for(const i of[...this.#s.values()])if(i.waitsOn===e.unit){if(t.kind!=="placed"){this.#f(i,s);continue}i.met.add(e.unit)}t.kind==="placed"&&(this.#P(e.unit),this.#c("apply",[e.unit]))}#P(e){const t=new Map([[e,!0]]);for(const s of this.#s.values()){const i=new Set;let n=s.unit;for(;n!==null&&!t.has(n)&&!i.has(n);)i.add(n),n=this.#s.get(n)?.waitsOn??null;const r=n!==null&&t.get(n)===!0;for(const h of i)t.set(h,r);if(r)for(const h of s.waiters)h.moved()}}#G(e){let t=e;const s=new Set([e]);for(let i=e.waitsOn===null?void 0:this.#s.get(e.waitsOn);i&&!s.has(i);i=i.waitsOn===null?void 0:this.#s.get(i.waitsOn))s.add(i),t=i;return{kind:"held",unit:t.unit,reason:t.held?.reason??"still placing"}}async#U(e,t,s){const i=t.members[0]?.work.entityId??null;if(e.held&&e.held.entityId!==null&&e.held.entityId!==i&&(e.held=null),await this.#Q(e,t))return!1;let n=await(0,c.outcomeOf)(()=>this.#a.run(t,()=>e.kind==="lane"&&e.emptied?e.unit:null));if(e.kind==="line"&&typeof n=="object"&&n.kind==="park"&&(0,A.windowEndForWait)(t,n.dependency)===null&&this.#K(e,t,n)&&(n=await(0,c.outcomeOf)(()=>this.#a.alone(t.members[0]))),n==="progress"||typeof n=="object"&&n.kind==="alone"){if(e.kind==="line")for(const r of t.members)(r.judgment==="waiting"||n!=="progress"&&r.work.entityId===n.entityId)&&this.#q(r.work.entityId);return this.#Z(e,n==="progress"?t.members.map(r=>r.work.entityId):[n.entityId])}if(n==="again")return e.held?.entityId===i&&(e.held=null),!0;if(n.advanced?.length&&this.#B(e,n.advanced),e.kind==="line"){const r=(0,A.windowEndForWait)(t,n.dependency);if(r!==null)return e.endsBefore=r,!0}return this.#ee(e,t,n,s),e.kind==="lane"&&this.#L(e),e.held.due}#K(e,t,s){const i=t.members[0].work.entityId;if(s.cause!==void 0||!(0,c.stepsAside)(t,i))return!1;const n=s.dependency?.entityIds??[i];return n.length===0||n.some(r=>r!==i)?!1:s.dependency?.producer==="capability"?!0:this.#j(e,t)>=exports.ENTITY_APPLY_SAME_ANSWERS}#j(e,t){const s=e.held,i=t.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#a.targetOf(t)?s.attempt:0)+1}async#Q(e,t){const s=e.held,i=t.members[0];return!s||i===void 0||s.entityId!==i.work.entityId||s.due||s.notBefore<=this.#e.now()||this.#a.targetOf(t)!==s.target||t.cutoff!==s.cutoff?!1:await this.#e.store.localWorkAfter(t.authorityId,i.work.entityId,s.kept??s.target)===null}#Z(e,t){return e.held&&(e.held.entityId===null||t.includes(e.held.entityId))&&(e.held=null),this.#B(e,t),!0}#B(e,t){e.kind==="lane"&&(this.#r=!0,this.#P(e.unit)),this.#c("apply",t);for(const s of this.#w())s!==e&&s.held?.releaseOnProgress&&!s.held.due&&(s.held.due=!0,this.#i(s))}#ee(e,t,s,i){if(s.dependency&&(0,o.assertApplyDependency)(s.dependency),s.blocker&&!s.dependency)throw new Error("Apply blocker must name the dependency that releases it");const n=t.members[0].work.entityId,r=e.held,h=this.#j(e,t),u=this.#C(h),a=s.again===!0&&h<exports.ENTITY_APPLY_SAME_ANSWERS,y={entityId:n,target:this.#a.targetOf(t),kept:t.members[0].work.kept,cutoff:t.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#e.now()+(a?0:u),releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#D(s.dependency,s.comparedAt??i):a,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};e.held=y,this.#R();const m=(0,o.heldWait)(r),p=(0,o.heldWait)(y);p&&JSON.stringify(p)!==JSON.stringify(m)&&this.#e.onWaiting?.(p),!(!s.report&&(s.dependency!==void 0||h<exports.ENTITY_APPLY_SAME_ANSWERS))&&this.#Y(new Error(`${g(e)} holds at ${n}, which ${s.releaseOnProgress?"is parked on a conflict":s.report?"failed":s.again?"keeps ending unplaced":"stands on ground that keeps moving"}, and will retry in ${u}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#W(e,t){if(e.kind==="lane"){for(const h of e.waiters)h.fail(t);e.waiters.clear()}const s=e.held,i=(s?.entityId===null?s.attempt:0)+1,n=this.#C(i),r=t instanceof Error?t.message:String(t);e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:i,notBefore:this.#e.now()+n,releaseOnProgress:!1,due:!1,reason:r},this.#R(),this.#Y(new Error(`${g(e)} faulted and will retry in ${n}ms (attempt ${i}): ${r}`,{cause:t}))}#Y(e){try{this.#b(e)}catch{}}#C(e){const t=Math.min(exports.ENTITY_APPLY_RETRY_MAX_MS,exports.ENTITY_APPLY_RETRY_BASE_MS*2**Math.min(e-1,16)),s=Math.max(0,Math.min(1,this.#e.schedule.random()));return Math.round(t*(.5+s))}#c(e,t){const s=++this.#m;for(const i of t??["*"])this.#S.set(`${e}:${i}`,s);for(const i of this.#w())(0,o.releaseApplyLine)(i,e,t)&&this.#i(i)}#D(e,t){return["*",...e.entityIds].some(s=>(this.#S.get(`${e.producer}:${s}`)??0)>t)}#R(){if(this.#t)return;let e=this.#p;for(const i of this.#w())i.held&&!i.held.due&&(e=Math.min(e,i.held.notBefore));if(e===1/0){this.#N();return}if(this.#y?.dueAt===e)return;this.#N();const t=Math.max(0,e-this.#e.now()),s=this.#e.schedule.schedule(t,()=>{this.#y=null,this.#x(e),this.#n()});this.#y={dueAt:e,cancel:d(()=>s.cancel(),"cancel")}}#x(e){let t=!1;for(const s of this.#w())s.held&&!s.held.due&&s.held.notBefore<=e&&(s.held.due=!0,this.#i(s),t=!0);return this.#p<=e&&(this.#p=1/0,this.#r=!0,t=!0),t}#N(){this.#y?.cancel(),this.#y=null}}exports.EntityApplyRail=I;const g=d(l=>l.kind==="line"?`entity Apply line ${l.authorityId}`:`entity Apply fetch of ${l.unit}`,"label");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amalgm/live",
|
|
3
|
-
"version": "0.2.81-main.
|
|
3
|
+
"version": "0.2.81-main.46558670594",
|
|
4
4
|
"description": "Portable realtime SDK for Amalgm — wire contracts, mutation discipline, and delivery state machines behind host-injected adapters.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist-cjs/index.js",
|
|
@@ -133,11 +133,11 @@
|
|
|
133
133
|
"dependencies": {
|
|
134
134
|
"@amalgm/core": "0.5.1-main.46384328664"
|
|
135
135
|
},
|
|
136
|
-
"gitHead": "
|
|
136
|
+
"gitHead": "5e3275aa5d7bf68b5657e9e9b3817ec09e006776",
|
|
137
137
|
"amalgmSource": {
|
|
138
138
|
"repository": "amalgm-inc/amalgm-live",
|
|
139
139
|
"branch": "main",
|
|
140
|
-
"commit": "
|
|
141
|
-
"occurrence": "
|
|
140
|
+
"commit": "5e3275aa5d7bf68b5657e9e9b3817ec09e006776",
|
|
141
|
+
"occurrence": "46558670594"
|
|
142
142
|
}
|
|
143
143
|
}
|