@milaboratories/pl-tree 1.6.8 → 1.6.10
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/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +150 -142
- package/dist/index.mjs.map +1 -1
- package/dist/state.d.ts.map +1 -1
- package/dist/synchronized_tree.d.ts +2 -0
- package/dist/synchronized_tree.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/state.ts +3 -5
- package/src/synchronized_tree.ts +27 -9
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var K=Object.defineProperty;var B=(o,e,t)=>e in o?K(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var c=(o,e,t)=>B(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@milaboratories/pl-client"),m=require("@milaboratories/computable"),b=require("@milaboratories/pl-errors"),p=require("@milaboratories/ts-helpers"),M=require("denque"),q=require("node:timers/promises");function U(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const J=U(q);function z(o,e){if(o!==void 0)return D(o,e)}function D(o,e){const t={};return o.value!==void 0&&(t.value=e(o.value)),o.error!==void 0&&(t.error=e(o.error)),t}class j extends Error{constructor(e){super(e)}}function H(o){return typeof o=="object"&&o!==null&&o.__pl_tree_type_marker__==="PlTreeEntry"}function Y(o){return typeof o=="object"&&o!==null&&o.__pl_tree_type_marker__==="PlTreeEntryAccessor"}function G(o){return typeof o=="object"&&o!==null&&o.__pl_tree_type_marker__==="PlTreeNodeAccessor"}class S{constructor(e,t){c(this,"__pl_tree_type_marker__","PlTreeEntry");this.accessorData=e,this.rid=t}createAccessor(e,t){return new T(this.accessorData,this.accessorData.treeProvider(),this.rid,{ctx:e,guard:t})}toJSON(){return this.toString()}toString(){return`[ENTRY:${g.resourceIdToString(this.rid)}]`}}function P(o,e,t,r,i){const n=new O(o,e,e.get(t.ctx.watcher,r),t);if(!i.ignoreError){const a=n.getError();if(a!==void 0)throw b.parsePlError(p.notEmpty(a.getDataAsString()),n.id,n.resourceType)}if(i.assertResourceType!==void 0&&(Array.isArray(i.assertResourceType)?i.assertResourceType.findIndex(a=>g.resourceTypesEqual(a,n.resourceType))===-1:!g.resourceTypesEqual(i.assertResourceType,n.resourceType)))throw new Error(`wrong resource type ${g.resourceTypeToString(n.resourceType)} but expected ${i.assertResourceType}`);return n}class T{constructor(e,t,r,i){c(this,"__pl_tree_type_marker__","PlTreeEntryAccessor");this.accessorData=e,this.tree=t,this.rid=r,this.instanceData=i}node(e={}){return this.instanceData.guard(),this.accessorData.hooks!==void 0&&this.instanceData.ctx.attacheHooks(this.accessorData.hooks),P(this.accessorData,this.tree,this.instanceData,this.rid,e)}}function Q(o,e){return o instanceof S?e.accessor(o).node().resourceInfo:o}class O{constructor(e,t,r,i){c(this,"__pl_tree_type_marker__","PlTreeNodeAccessor");c(this,"onUnstableLambda",e=>{this.instanceData.ctx.markUnstable(e)});this.accessorData=e,this.tree=t,this.resource=r,this.instanceData=i}get id(){return this.instanceData.guard(),this.resource.id}get originalId(){return this.instanceData.guard(),this.resource.originalResourceId}get resourceType(){return this.instanceData.guard(),this.resource.type}get resourceInfo(){return{id:this.id,type:this.resourceType}}getResourceFromTree(e,t){return P(this.accessorData,this.tree,this.instanceData,e,t)}traverse(...e){return this.traverseWithCommon({},...e)}traverseOrError(...e){return this.traverseOrErrorWithCommon({},...e)}traverseWithCommon(e,...t){const r=this.traverseOrErrorWithCommon(e,...t);if(r!==void 0){if(!r.ok)throw r.error;return r.value}}traverseOrErrorWithCommon(e,...t){let r=this;for(const i of t){const n=typeof i=="string"?{...e,field:i}:{...e,...i},a=r.getField(i);if(a===void 0||n.pureFieldErrorToUndefined&&a.value===void 0&&a.error!==void 0)return;if((!n.ignoreError||a.value===void 0)&&a.error!==void 0)return{ok:!1,error:b.parsePlError(p.notEmpty(a.error.getDataAsString()),r.id,r.resourceType,n.field)};if(a.value===void 0){if(n.errorIfFieldNotSet)return{ok:!1,error:new Error(`field have no assigned value ${n.field} of ${g.resourceIdToString(r.id)}`)};this.onUnstableLambda("unpopulated_field:"+n.field);return}r=a.value}return{ok:!0,value:r}}getField(e){this.instanceData.guard();const t=typeof e=="string"?{field:e}:e,r=this.resource.getField(this.instanceData.ctx.watcher,t,this.onUnstableLambda);if(r!==void 0)return D(r,i=>this.getResourceFromTree(i,{ignoreError:!0}))}getInputsLocked(){this.instanceData.guard();const e=this.resource.getInputsLocked(this.instanceData.ctx.watcher);return e||this.instanceData.ctx.markUnstable("inputs_unlocked:"+this.resourceType.name),e}getOutputsLocked(){this.instanceData.guard();const e=this.resource.getOutputsLocked(this.instanceData.ctx.watcher);return e||this.instanceData.ctx.markUnstable("outputs_unlocked:"+this.resourceType.name),e}getIsReadyOrError(){this.instanceData.guard();const e=this.resource.getIsReadyOrError(this.instanceData.ctx.watcher);return e||this.instanceData.ctx.markUnstable("not_ready:"+this.resourceType.name),e}getIsFinal(){return this.instanceData.guard(),this.resource.getIsFinal(this.instanceData.ctx.watcher)}getError(){this.instanceData.guard();const e=this.resource.getError(this.instanceData.ctx.watcher);if(e!==void 0)return this.getResourceFromTree(e,{})}getData(){return this.resource.data}getDataAsString(){return this.resource.getDataAsString()}getDataAsJson(){return this.resource.getDataAsJson()}listInputFields(){return this.instanceData.guard(),this.getInputsLocked(),this.resource.listInputFields(this.instanceData.ctx.watcher)}listOutputFields(){return this.instanceData.guard(),this.getOutputsLocked(),this.resource.listOutputFields(this.instanceData.ctx.watcher)}listDynamicFields(){return this.instanceData.guard(),this.resource.listDynamicFields(this.instanceData.ctx.watcher)}getKeyValue(e,t=!1){this.instanceData.guard();const r=this.resource.getKeyValue(this.instanceData.ctx.watcher,e);return r===void 0&&t&&this.instanceData.ctx.markUnstable("key_not_found_b:"+e),r}getKeyValueString(e){return this.getKeyValueAsString(e)}getKeyValueAsString(e,t=!1){this.instanceData.guard();const r=this.resource.getKeyValueString(this.instanceData.ctx.watcher,e);return r===void 0&&t&&this.instanceData.ctx.markUnstable("key_not_found_s:"+e),r}getKeyValueAsJson(e,t=!1){const r=this.resource.getKeyValueAsJson(this.instanceData.ctx.watcher,e);if(r===void 0){t&&this.instanceData.ctx.markUnstable("key_not_found_j:"+e);return}return r}toEntryAccessor(){return new T(this.accessorData,this.tree,this.id,this.instanceData)}persist(){return new S(this.accessorData,this.resource.id)}}class w extends Error{constructor(e){super(e)}}class _{constructor(e,t,r,i,n,a,s){c(this,"change",new m.ChangeSource);this.name=e,this.type=t,this.value=r,this.error=i,this.status=n,this.valueIsFinal=a,this.resourceVersion=s}get state(){return{name:this.name,type:this.type,status:this.status,value:this.value,error:this.error,valueIsFinal:this.valueIsFinal}}}const E=0,A=new TextDecoder;class ${constructor(e,t){c(this,"refCount",0);c(this,"version",E);c(this,"dataVersion",E);c(this,"fieldsMap",new Map);c(this,"kv",new Map);c(this,"resourceRemoved",new m.ChangeSource);c(this,"finalChanged",new m.ChangeSource);c(this,"resourceStateChange",new m.ChangeSource);c(this,"lockedChange",new m.ChangeSource);c(this,"inputAndServiceFieldListChanged",new m.ChangeSource);c(this,"outputFieldListChanged",new m.ChangeSource);c(this,"dynamicFieldListChanged",new m.ChangeSource);c(this,"kvChanged",new m.ChangeSource);c(this,"id");c(this,"originalResourceId");c(this,"kind");c(this,"type");c(this,"data");c(this,"dataAsString");c(this,"dataAsJson");c(this,"error");c(this,"inputsLocked");c(this,"outputsLocked");c(this,"resourceReady");c(this,"finalFlag");c(this,"_finalState",!1);c(this,"logger");this.id=e.id,this.originalResourceId=e.originalResourceId,this.kind=e.kind,this.type=e.type,this.data=e.data,this.error=e.error,this.inputsLocked=e.inputsLocked,this.outputsLocked=e.outputsLocked,this.resourceReady=e.resourceReady,this.finalFlag=e.final,this.logger=t}info(e){this.logger!==void 0&&this.logger.info(e)}warn(e){this.logger!==void 0&&this.logger.warn(e)}get final(){return this.finalFlag}get finalState(){return this._finalState}get fields(){return[...this.fieldsMap.values()]}getField(e,t,r=()=>{}){var a,s,f;const i=typeof t=="string"?{field:t}:t,n=this.fieldsMap.get(i.field);if(n===void 0){if(i.errorIfFieldNotFound||i.errorIfFieldNotSet)throw new Error(`Field "${i.field}" not found in resource ${g.resourceIdToString(this.id)}`);if(!this.inputsLocked)(a=this.inputAndServiceFieldListChanged)==null||a.attachWatcher(e);else if(i.assertFieldType==="Service"||i.assertFieldType==="Input"){if(i.allowPermanentAbsence)return;throw new Error(`Service or input field not found ${i.field}.`)}if(!this.outputsLocked)(s=this.outputFieldListChanged)==null||s.attachWatcher(e);else if(i.assertFieldType==="Output"){if(i.allowPermanentAbsence)return;throw new Error(`Output field not found ${i.field}.`)}(f=this.dynamicFieldListChanged)==null||f.attachWatcher(e),!this._finalState&&!i.stableIfNotFound&&r("field_not_found:"+i.field);return}else{if(i.assertFieldType!==void 0&&n.type!==i.assertFieldType)throw new Error(`Unexpected field type: expected ${i.assertFieldType} but got ${n.type} for the field name ${i.field}`);const h={};return g.isNotNullResourceId(n.value)&&(h.value=n.value),g.isNotNullResourceId(n.error)&&(h.error=n.error),h.value===void 0&&h.error===void 0&&r("field_not_resolved:"+i.field),n.change.attachWatcher(e),h}}getInputsLocked(e){var t;return this.inputsLocked||(t=this.resourceStateChange)==null||t.attachWatcher(e),this.inputsLocked}getOutputsLocked(e){var t;return this.outputsLocked||(t=this.resourceStateChange)==null||t.attachWatcher(e),this.outputsLocked}get isReadyOrError(){return this.error!==g.NullResourceId||this.resourceReady||this.originalResourceId!==g.NullResourceId}getIsFinal(e){var t;return(t=this.finalChanged)==null||t.attachWatcher(e),this._finalState}getIsReadyOrError(e){var t;return this.isReadyOrError||(t=this.resourceStateChange)==null||t.attachWatcher(e),this.isReadyOrError}getError(e){var t;if(g.isNullResourceId(this.error)){(t=this.resourceStateChange)==null||t.attachWatcher(e);return}else return this.error}listInputFields(e){var r;const t=[];return this.fieldsMap.forEach((i,n)=>{(i.type==="Input"||i.type==="Service")&&t.push(n)}),this.inputsLocked||(r=this.inputAndServiceFieldListChanged)==null||r.attachWatcher(e),t}listOutputFields(e){var r;const t=[];return this.fieldsMap.forEach((i,n)=>{i.type==="Output"&&t.push(n)}),this.outputsLocked||(r=this.outputFieldListChanged)==null||r.attachWatcher(e),t}listDynamicFields(e){var r;const t=[];return this.fieldsMap.forEach((i,n)=>{i.type!=="Input"&&i.type!=="Output"&&t.push(n)}),(r=this.dynamicFieldListChanged)==null||r.attachWatcher(e),t}getKeyValue(e,t){var r;return(r=this.kvChanged)==null||r.attachWatcher(e),this.kv.get(t)}getKeyValueString(e,t){const r=this.getKeyValue(e,t);if(r!==void 0)return A.decode(r)}getKeyValueAsJson(e,t){const r=this.getKeyValue(e,t);if(r!==void 0)return p.cachedDeserialize(r)}getDataAsString(){if(this.data!==void 0)return this.dataAsString===void 0&&(this.dataAsString=A.decode(this.data)),this.dataAsString}getDataAsJson(){if(this.data!==void 0)return this.dataAsJson===void 0&&(this.dataAsJson=p.cachedDeserialize(this.data)),this.dataAsJson}verifyReadyState(){if(this.resourceReady&&!this.inputsLocked)throw new Error(`ready without input or output lock: ${g.stringifyWithResourceId(this.basicState)}`)}get basicState(){return{id:this.id,kind:this.kind,type:this.type,data:this.data,resourceReady:this.resourceReady,inputsLocked:this.inputsLocked,outputsLocked:this.outputsLocked,error:this.error,originalResourceId:this.originalResourceId,final:this.finalFlag}}get extendedState(){return{...this.basicState,fields:this.fields,kv:Array.from(this.kv.entries()).map(([e,t])=>({key:e,value:t}))}}markFinal(){this._finalState||(this._finalState=!0,p.notEmpty(this.finalChanged).markChanged(),this.finalChanged=void 0,this.resourceStateChange=void 0,this.dynamicFieldListChanged=void 0,this.inputAndServiceFieldListChanged=void 0,this.outputFieldListChanged=void 0,this.lockedChange=void 0)}markAllChanged(){var e,t,r,i,n,a,s;this.fieldsMap.forEach(f=>f.change.markChanged()),(e=this.finalChanged)==null||e.markChanged(),(t=this.resourceStateChange)==null||t.markChanged(),(r=this.lockedChange)==null||r.markChanged(),(i=this.inputAndServiceFieldListChanged)==null||i.markChanged(),(n=this.outputFieldListChanged)==null||n.markChanged(),(a=this.dynamicFieldListChanged)==null||a.markChanged(),(s=this.kvChanged)==null||s.markChanged(),this.resourceRemoved.markChanged()}}class I{constructor(e,t){c(this,"resources",new Map);c(this,"resourcesAdded",new m.ChangeSource);c(this,"_isValid",!0);c(this,"invalidationMessage");this.root=e,this.isFinalPredicate=t}forEachResource(e){this.resources.forEach(t=>e(t))}checkValid(){if(!this._isValid)throw new Error(this.invalidationMessage??"tree is in invalid state")}get(e,t){this.checkValid();const r=this.resources.get(t);if(r===void 0)throw this.resourcesAdded.attachWatcher(e),new Error(`resource ${g.resourceIdToString(t)} not found in the tree`);return r.resourceRemoved.attachWatcher(e),r}updateFromResourceData(e,t=!1){this.checkValid();const r=[],i=[];for(const a of e){let s=this.resources.get(a.id);const f=s==null?void 0:s.basicState,h=l=>{const{fields:k,...u}=a;throw this.invalidateTree(),new w(`Unexpected resource state transition (${l}): ${g.stringifyWithResourceId(u)} -> ${g.stringifyWithResourceId(f)}`)};if(s!==void 0){s.finalState&&h("resource state can be updated after it is marked as final");let l=!1;s.version+=1,s.originalResourceId!==a.originalResourceId&&(s.originalResourceId!==g.NullResourceId&&h("originalResourceId can't change after it is set"),s.originalResourceId=a.originalResourceId,p.notEmpty(s.resourceStateChange).markChanged(),l=!0),s.error!==a.error&&(g.isNotNullResourceId(s.error)&&h("resource can't change attached error after it is set"),s.error=a.error,r.push(s.error),p.notEmpty(s.resourceStateChange).markChanged(),l=!0);for(const u of a.fields){let d=s.fieldsMap.get(u.name);d?(d.type!==u.type&&(d.type!=="Dynamic"&&h(`field changed type ${d.type} -> ${u.type}`),p.notEmpty(s.dynamicFieldListChanged).markChanged(),(d.type==="Input"||d.type==="Service")&&(s.inputsLocked&&h(`adding input field "${u.name}", while corresponding list is locked`),p.notEmpty(s.inputAndServiceFieldListChanged).markChanged()),d.type==="Output"&&(s.outputsLocked&&h(`adding output field "${u.name}", while corresponding list is locked`),p.notEmpty(s.outputFieldListChanged).markChanged()),d.type=u.type,d.change.markChanged(),l=!0),d.value!==u.value&&(g.isNotNullResourceId(d.value)&&i.push(d.value),d.value=u.value,g.isNotNullResourceId(u.value)&&r.push(u.value),d.change.markChanged(),l=!0),d.error!==u.error&&(g.isNotNullResourceId(d.error)&&i.push(d.error),d.error=u.error,g.isNotNullResourceId(u.error)&&r.push(u.error),d.change.markChanged(),l=!0),d.status!==u.status&&(d.status=u.status,d.change.markChanged(),l=!0),d.valueIsFinal!==u.valueIsFinal&&(d.valueIsFinal=u.valueIsFinal,d.change.markChanged(),l=!0),d.resourceVersion=s.version):(d=new _(u.name,u.type,u.value,u.error,u.status,u.valueIsFinal,s.version),g.isNotNullResourceId(u.value)&&r.push(u.value),g.isNotNullResourceId(u.error)&&r.push(u.error),u.type==="Input"||u.type==="Service"?(s.inputsLocked&&h(`adding ${u.type} (${u.name}) field while inputs locked`),p.notEmpty(s.inputAndServiceFieldListChanged).markChanged()):u.type==="Output"?(s.outputsLocked&&h(`adding ${u.type} (${u.name}) field while outputs locked`),p.notEmpty(s.outputFieldListChanged).markChanged()):p.notEmpty(s.dynamicFieldListChanged).markChanged(),s.fieldsMap.set(u.name,d),l=!0)}if(s.fieldsMap.forEach((u,d,y)=>{u.resourceVersion!==s.version&&((u.type==="Input"||u.type==="Service"||u.type==="Output")&&h(`removal of ${u.type} field ${d}`),u.change.markChanged(),y.delete(d),g.isNotNullResourceId(u.value)&&i.push(u.value),g.isNotNullResourceId(u.error)&&i.push(u.error),p.notEmpty(s.dynamicFieldListChanged).markChanged())}),s.inputsLocked!==a.inputsLocked&&(s.inputsLocked&&h("inputs unlocking is not permitted"),s.inputsLocked=a.inputsLocked,p.notEmpty(s.lockedChange).markChanged(),l=!0),s.outputsLocked!==a.outputsLocked&&(s.outputsLocked&&h("outputs unlocking is not permitted"),s.outputsLocked=a.outputsLocked,p.notEmpty(s.lockedChange).markChanged(),l=!0),s.resourceReady!==a.resourceReady){const u=s.resourceReady;s.resourceReady=a.resourceReady,s.verifyReadyState(),s.isReadyOrError||h(`resource can't lose it's ready or error state (ready state before ${u})`),p.notEmpty(s.resourceStateChange).markChanged(),l=!0}let k=!1;for(const u of a.kv){const d=s.kv.get(u.key);(d===void 0||Buffer.compare(d,u.value)!==0)&&(s.kv.set(u.key,u.value),k=!0)}if(s.kv.size>a.kv.length){const u=new Set(a.kv.map(d=>d.key));s.kv.forEach((d,y,v)=>{u.has(y)||v.delete(y)}),k=!0}k&&p.notEmpty(s.kvChanged).markChanged(),l&&(s.dataVersion=s.version,this.isFinalPredicate(s)&&s.markFinal())}else{s=new $(a),s.verifyReadyState(),g.isNotNullResourceId(s.error)&&r.push(s.error);for(const l of a.fields){const k=new _(l.name,l.type,l.value,l.error,l.status,l.valueIsFinal,E);g.isNotNullResourceId(l.value)&&r.push(l.value),g.isNotNullResourceId(l.error)&&r.push(l.error),s.fieldsMap.set(l.name,k)}for(const l of a.kv)s.kv.set(l.key,l.value);this.isFinalPredicate(s)&&s.markFinal(),this.resources.set(s.id,s),this.resourcesAdded.markChanged()}}for(const a of r){const s=this.resources.get(a);if(!s)throw this.invalidateTree(),new w(`orphan resource ${a}`);s.refCount++}let n=i;for(;n.length>0;){const a=[];for(const s of n){const f=this.resources.get(s);if(!f)throw this.invalidateTree(),new w(`orphan resource ${s}`);f.refCount--,f.refCount===0&&f.id!==this.root&&(f.fieldsMap.forEach(h=>{g.isNotNullResourceId(h.value)&&a.push(h.value),g.isNotNullResourceId(h.error)&&a.push(h.error),h.change.markChanged()}),g.isNotNullResourceId(f.error)&&a.push(f.error),f.resourceRemoved.markChanged(),this.resources.delete(s))}n=a}if(!t){for(const a of e)if(!this.resources.has(a.id))throw this.invalidateTree(),new w(`orphan input resource ${a.id}`)}}accessor(e=this.root){return this.checkValid(),this.entry(e)}entry(e=this.root){return this.checkValid(),new S({treeProvider:()=>this},e)}invalidateTree(e){this._isValid=!1,this.invalidationMessage=e,this.resources.forEach(t=>{t.markAllChanged()})}dumpState(){return Array.from(this.resources.values()).map(e=>e.extendedState)}}function x(o,e){const t=[],r=new Set;return o.forEachResource(i=>{i.finalState?r.add(i.id):t.push(i.id)}),t.length===0&&r.size===0&&t.push(o.root),{seedResources:t,finalResources:r,pruningFunction:e}}function C(){return{requests:0,roundTrips:0,retrievedResources:0,retrievedFields:0,retrievedKeyValues:0,retrievedResourceDataBytes:0,retrievedKeyValueBytes:0,prunedFields:0,finalResourcesSkipped:0,millisSpent:0}}function X(o){let e=`Requests: ${o.requests}
|
|
2
|
-
`;return e+=`Total time: ${
|
|
1
|
+
"use strict";var W=Object.defineProperty;var K=(o,e,t)=>e in o?W(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var c=(o,e,t)=>K(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@milaboratories/pl-client"),k=require("@milaboratories/computable"),A=require("@milaboratories/pl-errors"),g=require("@milaboratories/ts-helpers"),B=require("denque"),M=require("node:timers/promises");function U(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const q=U(M);function J(o,e){if(o!==void 0)return I(o,e)}function I(o,e){const t={};return o.value!==void 0&&(t.value=e(o.value)),o.error!==void 0&&(t.error=e(o.error)),t}class z extends Error{constructor(e){super(e)}}function j(o){return typeof o=="object"&&o!==null&&o.__pl_tree_type_marker__==="PlTreeEntry"}function H(o){return typeof o=="object"&&o!==null&&o.__pl_tree_type_marker__==="PlTreeEntryAccessor"}function Y(o){return typeof o=="object"&&o!==null&&o.__pl_tree_type_marker__==="PlTreeNodeAccessor"}class S{constructor(e,t){c(this,"__pl_tree_type_marker__","PlTreeEntry");this.accessorData=e,this.rid=t}createAccessor(e,t){return new T(this.accessorData,this.accessorData.treeProvider(),this.rid,{ctx:e,guard:t})}toJSON(){return this.toString()}toString(){return`[ENTRY:${p.resourceIdToString(this.rid)}]`}}function b(o,e,t,r,a){const n=new P(o,e,e.get(t.ctx.watcher,r),t);if(!a.ignoreError){const i=n.getError();if(i!==void 0)throw A.parsePlError(g.notEmpty(i.getDataAsString()),n.id,n.resourceType)}if(a.assertResourceType!==void 0&&(Array.isArray(a.assertResourceType)?a.assertResourceType.findIndex(i=>p.resourceTypesEqual(i,n.resourceType))===-1:!p.resourceTypesEqual(a.assertResourceType,n.resourceType)))throw new Error(`wrong resource type ${p.resourceTypeToString(n.resourceType)} but expected ${a.assertResourceType}`);return n}class T{constructor(e,t,r,a){c(this,"__pl_tree_type_marker__","PlTreeEntryAccessor");this.accessorData=e,this.tree=t,this.rid=r,this.instanceData=a}node(e={}){return this.instanceData.guard(),this.accessorData.hooks!==void 0&&this.instanceData.ctx.attacheHooks(this.accessorData.hooks),b(this.accessorData,this.tree,this.instanceData,this.rid,e)}}function G(o,e){return o instanceof S?e.accessor(o).node().resourceInfo:o}class P{constructor(e,t,r,a){c(this,"__pl_tree_type_marker__","PlTreeNodeAccessor");c(this,"onUnstableLambda",e=>{this.instanceData.ctx.markUnstable(e)});this.accessorData=e,this.tree=t,this.resource=r,this.instanceData=a}get id(){return this.instanceData.guard(),this.resource.id}get originalId(){return this.instanceData.guard(),this.resource.originalResourceId}get resourceType(){return this.instanceData.guard(),this.resource.type}get resourceInfo(){return{id:this.id,type:this.resourceType}}getResourceFromTree(e,t){return b(this.accessorData,this.tree,this.instanceData,e,t)}traverse(...e){return this.traverseWithCommon({},...e)}traverseOrError(...e){return this.traverseOrErrorWithCommon({},...e)}traverseWithCommon(e,...t){const r=this.traverseOrErrorWithCommon(e,...t);if(r!==void 0){if(!r.ok)throw r.error;return r.value}}traverseOrErrorWithCommon(e,...t){let r=this;for(const a of t){const n=typeof a=="string"?{...e,field:a}:{...e,...a},i=r.getField(a);if(i===void 0||n.pureFieldErrorToUndefined&&i.value===void 0&&i.error!==void 0)return;if((!n.ignoreError||i.value===void 0)&&i.error!==void 0)return{ok:!1,error:A.parsePlError(g.notEmpty(i.error.getDataAsString()),r.id,r.resourceType,n.field)};if(i.value===void 0){if(n.errorIfFieldNotSet)return{ok:!1,error:new Error(`field have no assigned value ${n.field} of ${p.resourceIdToString(r.id)}`)};this.onUnstableLambda("unpopulated_field:"+n.field);return}r=i.value}return{ok:!0,value:r}}getField(e){this.instanceData.guard();const t=typeof e=="string"?{field:e}:e,r=this.resource.getField(this.instanceData.ctx.watcher,t,this.onUnstableLambda);if(r!==void 0)return I(r,a=>this.getResourceFromTree(a,{ignoreError:!0}))}getInputsLocked(){this.instanceData.guard();const e=this.resource.getInputsLocked(this.instanceData.ctx.watcher);return e||this.instanceData.ctx.markUnstable("inputs_unlocked:"+this.resourceType.name),e}getOutputsLocked(){this.instanceData.guard();const e=this.resource.getOutputsLocked(this.instanceData.ctx.watcher);return e||this.instanceData.ctx.markUnstable("outputs_unlocked:"+this.resourceType.name),e}getIsReadyOrError(){this.instanceData.guard();const e=this.resource.getIsReadyOrError(this.instanceData.ctx.watcher);return e||this.instanceData.ctx.markUnstable("not_ready:"+this.resourceType.name),e}getIsFinal(){return this.instanceData.guard(),this.resource.getIsFinal(this.instanceData.ctx.watcher)}getError(){this.instanceData.guard();const e=this.resource.getError(this.instanceData.ctx.watcher);if(e!==void 0)return this.getResourceFromTree(e,{})}getData(){return this.resource.data}getDataAsString(){return this.resource.getDataAsString()}getDataAsJson(){return this.resource.getDataAsJson()}listInputFields(){return this.instanceData.guard(),this.getInputsLocked(),this.resource.listInputFields(this.instanceData.ctx.watcher)}listOutputFields(){return this.instanceData.guard(),this.getOutputsLocked(),this.resource.listOutputFields(this.instanceData.ctx.watcher)}listDynamicFields(){return this.instanceData.guard(),this.resource.listDynamicFields(this.instanceData.ctx.watcher)}getKeyValue(e,t=!1){this.instanceData.guard();const r=this.resource.getKeyValue(this.instanceData.ctx.watcher,e);return r===void 0&&t&&this.instanceData.ctx.markUnstable("key_not_found_b:"+e),r}getKeyValueString(e){return this.getKeyValueAsString(e)}getKeyValueAsString(e,t=!1){this.instanceData.guard();const r=this.resource.getKeyValueString(this.instanceData.ctx.watcher,e);return r===void 0&&t&&this.instanceData.ctx.markUnstable("key_not_found_s:"+e),r}getKeyValueAsJson(e,t=!1){const r=this.resource.getKeyValueAsJson(this.instanceData.ctx.watcher,e);if(r===void 0){t&&this.instanceData.ctx.markUnstable("key_not_found_j:"+e);return}return r}toEntryAccessor(){return new T(this.accessorData,this.tree,this.id,this.instanceData)}persist(){return new S(this.accessorData,this.resource.id)}}class w extends Error{constructor(e){super(e)}}class _{constructor(e,t,r,a,n,i,s){c(this,"change",new k.ChangeSource);this.name=e,this.type=t,this.value=r,this.error=a,this.status=n,this.valueIsFinal=i,this.resourceVersion=s}get state(){return{name:this.name,type:this.type,status:this.status,value:this.value,error:this.error,valueIsFinal:this.valueIsFinal}}}const E=0;class ${constructor(e,t){c(this,"refCount",0);c(this,"version",E);c(this,"dataVersion",E);c(this,"fieldsMap",new Map);c(this,"kv",new Map);c(this,"resourceRemoved",new k.ChangeSource);c(this,"finalChanged",new k.ChangeSource);c(this,"resourceStateChange",new k.ChangeSource);c(this,"lockedChange",new k.ChangeSource);c(this,"inputAndServiceFieldListChanged",new k.ChangeSource);c(this,"outputFieldListChanged",new k.ChangeSource);c(this,"dynamicFieldListChanged",new k.ChangeSource);c(this,"kvChanged",new k.ChangeSource);c(this,"id");c(this,"originalResourceId");c(this,"kind");c(this,"type");c(this,"data");c(this,"dataAsString");c(this,"dataAsJson");c(this,"error");c(this,"inputsLocked");c(this,"outputsLocked");c(this,"resourceReady");c(this,"finalFlag");c(this,"_finalState",!1);c(this,"logger");this.id=e.id,this.originalResourceId=e.originalResourceId,this.kind=e.kind,this.type=e.type,this.data=e.data,this.error=e.error,this.inputsLocked=e.inputsLocked,this.outputsLocked=e.outputsLocked,this.resourceReady=e.resourceReady,this.finalFlag=e.final,this.logger=t}info(e){this.logger!==void 0&&this.logger.info(e)}warn(e){this.logger!==void 0&&this.logger.warn(e)}get final(){return this.finalFlag}get finalState(){return this._finalState}get fields(){return[...this.fieldsMap.values()]}getField(e,t,r=()=>{}){var i,s,f;const a=typeof t=="string"?{field:t}:t,n=this.fieldsMap.get(a.field);if(n===void 0){if(a.errorIfFieldNotFound||a.errorIfFieldNotSet)throw new Error(`Field "${a.field}" not found in resource ${p.resourceIdToString(this.id)}`);if(!this.inputsLocked)(i=this.inputAndServiceFieldListChanged)==null||i.attachWatcher(e);else if(a.assertFieldType==="Service"||a.assertFieldType==="Input"){if(a.allowPermanentAbsence)return;throw new Error(`Service or input field not found ${a.field}.`)}if(!this.outputsLocked)(s=this.outputFieldListChanged)==null||s.attachWatcher(e);else if(a.assertFieldType==="Output"){if(a.allowPermanentAbsence)return;throw new Error(`Output field not found ${a.field}.`)}(f=this.dynamicFieldListChanged)==null||f.attachWatcher(e),!this._finalState&&!a.stableIfNotFound&&r("field_not_found:"+a.field);return}else{if(a.assertFieldType!==void 0&&n.type!==a.assertFieldType)throw new Error(`Unexpected field type: expected ${a.assertFieldType} but got ${n.type} for the field name ${a.field}`);const h={};return p.isNotNullResourceId(n.value)&&(h.value=n.value),p.isNotNullResourceId(n.error)&&(h.error=n.error),h.value===void 0&&h.error===void 0&&r("field_not_resolved:"+a.field),n.change.attachWatcher(e),h}}getInputsLocked(e){var t;return this.inputsLocked||(t=this.resourceStateChange)==null||t.attachWatcher(e),this.inputsLocked}getOutputsLocked(e){var t;return this.outputsLocked||(t=this.resourceStateChange)==null||t.attachWatcher(e),this.outputsLocked}get isReadyOrError(){return this.error!==p.NullResourceId||this.resourceReady||this.originalResourceId!==p.NullResourceId}getIsFinal(e){var t;return(t=this.finalChanged)==null||t.attachWatcher(e),this._finalState}getIsReadyOrError(e){var t;return this.isReadyOrError||(t=this.resourceStateChange)==null||t.attachWatcher(e),this.isReadyOrError}getError(e){var t;if(p.isNullResourceId(this.error)){(t=this.resourceStateChange)==null||t.attachWatcher(e);return}else return this.error}listInputFields(e){var r;const t=[];return this.fieldsMap.forEach((a,n)=>{(a.type==="Input"||a.type==="Service")&&t.push(n)}),this.inputsLocked||(r=this.inputAndServiceFieldListChanged)==null||r.attachWatcher(e),t}listOutputFields(e){var r;const t=[];return this.fieldsMap.forEach((a,n)=>{a.type==="Output"&&t.push(n)}),this.outputsLocked||(r=this.outputFieldListChanged)==null||r.attachWatcher(e),t}listDynamicFields(e){var r;const t=[];return this.fieldsMap.forEach((a,n)=>{a.type!=="Input"&&a.type!=="Output"&&t.push(n)}),(r=this.dynamicFieldListChanged)==null||r.attachWatcher(e),t}getKeyValue(e,t){var r;return(r=this.kvChanged)==null||r.attachWatcher(e),this.kv.get(t)}getKeyValueString(e,t){const r=this.getKeyValue(e,t);if(r!==void 0)return g.cachedDecode(r)}getKeyValueAsJson(e,t){const r=this.getKeyValue(e,t);if(r!==void 0)return g.cachedDeserialize(r)}getDataAsString(){if(this.data!==void 0)return this.dataAsString===void 0&&(this.dataAsString=g.cachedDecode(this.data)),this.dataAsString}getDataAsJson(){if(this.data!==void 0)return this.dataAsJson===void 0&&(this.dataAsJson=g.cachedDeserialize(this.data)),this.dataAsJson}verifyReadyState(){if(this.resourceReady&&!this.inputsLocked)throw new Error(`ready without input or output lock: ${p.stringifyWithResourceId(this.basicState)}`)}get basicState(){return{id:this.id,kind:this.kind,type:this.type,data:this.data,resourceReady:this.resourceReady,inputsLocked:this.inputsLocked,outputsLocked:this.outputsLocked,error:this.error,originalResourceId:this.originalResourceId,final:this.finalFlag}}get extendedState(){return{...this.basicState,fields:this.fields,kv:Array.from(this.kv.entries()).map(([e,t])=>({key:e,value:t}))}}markFinal(){this._finalState||(this._finalState=!0,g.notEmpty(this.finalChanged).markChanged(),this.finalChanged=void 0,this.resourceStateChange=void 0,this.dynamicFieldListChanged=void 0,this.inputAndServiceFieldListChanged=void 0,this.outputFieldListChanged=void 0,this.lockedChange=void 0)}markAllChanged(){var e,t,r,a,n,i,s;this.fieldsMap.forEach(f=>f.change.markChanged()),(e=this.finalChanged)==null||e.markChanged(),(t=this.resourceStateChange)==null||t.markChanged(),(r=this.lockedChange)==null||r.markChanged(),(a=this.inputAndServiceFieldListChanged)==null||a.markChanged(),(n=this.outputFieldListChanged)==null||n.markChanged(),(i=this.dynamicFieldListChanged)==null||i.markChanged(),(s=this.kvChanged)==null||s.markChanged(),this.resourceRemoved.markChanged()}}class D{constructor(e,t){c(this,"resources",new Map);c(this,"resourcesAdded",new k.ChangeSource);c(this,"_isValid",!0);c(this,"invalidationMessage");this.root=e,this.isFinalPredicate=t}forEachResource(e){this.resources.forEach(t=>e(t))}checkValid(){if(!this._isValid)throw new Error(this.invalidationMessage??"tree is in invalid state")}get(e,t){this.checkValid();const r=this.resources.get(t);if(r===void 0)throw this.resourcesAdded.attachWatcher(e),new Error(`resource ${p.resourceIdToString(t)} not found in the tree`);return r.resourceRemoved.attachWatcher(e),r}updateFromResourceData(e,t=!1){this.checkValid();const r=[],a=[];for(const i of e){let s=this.resources.get(i.id);const f=s==null?void 0:s.basicState,h=l=>{const{fields:m,...u}=i;throw this.invalidateTree(),new w(`Unexpected resource state transition (${l}): ${p.stringifyWithResourceId(u)} -> ${p.stringifyWithResourceId(f)}`)};if(s!==void 0){s.finalState&&h("resource state can be updated after it is marked as final");let l=!1;s.version+=1,s.originalResourceId!==i.originalResourceId&&(s.originalResourceId!==p.NullResourceId&&h("originalResourceId can't change after it is set"),s.originalResourceId=i.originalResourceId,g.notEmpty(s.resourceStateChange).markChanged(),l=!0),s.error!==i.error&&(p.isNotNullResourceId(s.error)&&h("resource can't change attached error after it is set"),s.error=i.error,r.push(s.error),g.notEmpty(s.resourceStateChange).markChanged(),l=!0);for(const u of i.fields){let d=s.fieldsMap.get(u.name);d?(d.type!==u.type&&(d.type!=="Dynamic"&&h(`field changed type ${d.type} -> ${u.type}`),g.notEmpty(s.dynamicFieldListChanged).markChanged(),(d.type==="Input"||d.type==="Service")&&(s.inputsLocked&&h(`adding input field "${u.name}", while corresponding list is locked`),g.notEmpty(s.inputAndServiceFieldListChanged).markChanged()),d.type==="Output"&&(s.outputsLocked&&h(`adding output field "${u.name}", while corresponding list is locked`),g.notEmpty(s.outputFieldListChanged).markChanged()),d.type=u.type,d.change.markChanged(),l=!0),d.value!==u.value&&(p.isNotNullResourceId(d.value)&&a.push(d.value),d.value=u.value,p.isNotNullResourceId(u.value)&&r.push(u.value),d.change.markChanged(),l=!0),d.error!==u.error&&(p.isNotNullResourceId(d.error)&&a.push(d.error),d.error=u.error,p.isNotNullResourceId(u.error)&&r.push(u.error),d.change.markChanged(),l=!0),d.status!==u.status&&(d.status=u.status,d.change.markChanged(),l=!0),d.valueIsFinal!==u.valueIsFinal&&(d.valueIsFinal=u.valueIsFinal,d.change.markChanged(),l=!0),d.resourceVersion=s.version):(d=new _(u.name,u.type,u.value,u.error,u.status,u.valueIsFinal,s.version),p.isNotNullResourceId(u.value)&&r.push(u.value),p.isNotNullResourceId(u.error)&&r.push(u.error),u.type==="Input"||u.type==="Service"?(s.inputsLocked&&h(`adding ${u.type} (${u.name}) field while inputs locked`),g.notEmpty(s.inputAndServiceFieldListChanged).markChanged()):u.type==="Output"?(s.outputsLocked&&h(`adding ${u.type} (${u.name}) field while outputs locked`),g.notEmpty(s.outputFieldListChanged).markChanged()):g.notEmpty(s.dynamicFieldListChanged).markChanged(),s.fieldsMap.set(u.name,d),l=!0)}if(s.fieldsMap.forEach((u,d,y)=>{u.resourceVersion!==s.version&&((u.type==="Input"||u.type==="Service"||u.type==="Output")&&h(`removal of ${u.type} field ${d}`),u.change.markChanged(),y.delete(d),p.isNotNullResourceId(u.value)&&a.push(u.value),p.isNotNullResourceId(u.error)&&a.push(u.error),g.notEmpty(s.dynamicFieldListChanged).markChanged())}),s.inputsLocked!==i.inputsLocked&&(s.inputsLocked&&h("inputs unlocking is not permitted"),s.inputsLocked=i.inputsLocked,g.notEmpty(s.lockedChange).markChanged(),l=!0),s.outputsLocked!==i.outputsLocked&&(s.outputsLocked&&h("outputs unlocking is not permitted"),s.outputsLocked=i.outputsLocked,g.notEmpty(s.lockedChange).markChanged(),l=!0),s.resourceReady!==i.resourceReady){const u=s.resourceReady;s.resourceReady=i.resourceReady,s.verifyReadyState(),s.isReadyOrError||h(`resource can't lose it's ready or error state (ready state before ${u})`),g.notEmpty(s.resourceStateChange).markChanged(),l=!0}let m=!1;for(const u of i.kv){const d=s.kv.get(u.key);(d===void 0||Buffer.compare(d,u.value)!==0)&&(s.kv.set(u.key,u.value),m=!0)}if(s.kv.size>i.kv.length){const u=new Set(i.kv.map(d=>d.key));s.kv.forEach((d,y,v)=>{u.has(y)||v.delete(y)}),m=!0}m&&g.notEmpty(s.kvChanged).markChanged(),l&&(s.dataVersion=s.version,this.isFinalPredicate(s)&&s.markFinal())}else{s=new $(i),s.verifyReadyState(),p.isNotNullResourceId(s.error)&&r.push(s.error);for(const l of i.fields){const m=new _(l.name,l.type,l.value,l.error,l.status,l.valueIsFinal,E);p.isNotNullResourceId(l.value)&&r.push(l.value),p.isNotNullResourceId(l.error)&&r.push(l.error),s.fieldsMap.set(l.name,m)}for(const l of i.kv)s.kv.set(l.key,l.value);this.isFinalPredicate(s)&&s.markFinal(),this.resources.set(s.id,s),this.resourcesAdded.markChanged()}}for(const i of r){const s=this.resources.get(i);if(!s)throw this.invalidateTree(),new w(`orphan resource ${i}`);s.refCount++}let n=a;for(;n.length>0;){const i=[];for(const s of n){const f=this.resources.get(s);if(!f)throw this.invalidateTree(),new w(`orphan resource ${s}`);f.refCount--,f.refCount===0&&f.id!==this.root&&(f.fieldsMap.forEach(h=>{p.isNotNullResourceId(h.value)&&i.push(h.value),p.isNotNullResourceId(h.error)&&i.push(h.error),h.change.markChanged()}),p.isNotNullResourceId(f.error)&&i.push(f.error),f.resourceRemoved.markChanged(),this.resources.delete(s))}n=i}if(!t){for(const i of e)if(!this.resources.has(i.id))throw this.invalidateTree(),new w(`orphan input resource ${i.id}`)}}accessor(e=this.root){return this.checkValid(),this.entry(e)}entry(e=this.root){return this.checkValid(),new S({treeProvider:()=>this},e)}invalidateTree(e){this._isValid=!1,this.invalidationMessage=e,this.resources.forEach(t=>{t.markAllChanged()})}dumpState(){return Array.from(this.resources.values()).map(e=>e.extendedState)}}function O(o,e){const t=[],r=new Set;return o.forEachResource(a=>{a.finalState?r.add(a.id):t.push(a.id)}),t.length===0&&r.size===0&&t.push(o.root),{seedResources:t,finalResources:r,pruningFunction:e}}function C(){return{requests:0,roundTrips:0,retrievedResources:0,retrievedFields:0,retrievedKeyValues:0,retrievedResourceDataBytes:0,retrievedKeyValueBytes:0,prunedFields:0,finalResourcesSkipped:0,millisSpent:0}}function Q(o){let e=`Requests: ${o.requests}
|
|
2
|
+
`;return e+=`Total time: ${g.msToHumanReadable(o.millisSpent)}
|
|
3
3
|
`,e+=`Round-trips: ${o.roundTrips}
|
|
4
4
|
`,e+=`Resources: ${o.retrievedResources}
|
|
5
5
|
`,e+=`Fields: ${o.retrievedFields}
|
|
@@ -7,5 +7,5 @@
|
|
|
7
7
|
`,e+=`Data Bytes: ${o.retrievedResourceDataBytes}
|
|
8
8
|
`,e+=`KV Bytes: ${o.retrievedKeyValueBytes}
|
|
9
9
|
`,e+=`Pruned fields: ${o.prunedFields}
|
|
10
|
-
`,e+=`Final resources skipped: ${o.finalResourcesSkipped}`,e}async function
|
|
10
|
+
`,e+=`Final resources skipped: ${o.finalResourcesSkipped}`,e}async function x(o,e,t){var d;const r=Date.now();t&&t.requests++;const{seedResources:a,finalResources:n,pruningFunction:i}=e,s=new B;let f=!0,h=0;const l=new Set,m=y=>{if(p.isNullResourceId(y)||l.has(y))return;if(n.has(y)){t&&t.finalResourcesSkipped++;return}l.add(y);const v=o.getResourceDataIfExists(y,!0),R=o.listKeyValuesIfResourceExists(y),V=f;f&&(f=!1),s.push((async()=>{const[F,N]=await Promise.all([v,R]);if(V&&(h++,f=!0),F!==void 0){if(N===void 0)throw new Error("Inconsistent replies");return{...F,kv:N}}})())};a.forEach(y=>m(y));const u=[];for(;;){const y=s.shift();if(y===void 0)break;let v=await y;if(v!==void 0){if(i!==void 0){const R=i(v);t&&(t.prunedFields+=v.fields.length-R.length),v={...v,fields:R}}m(v.error);for(const R of v.fields)m(R.value),m(R.error);if(t){t.retrievedResources++,t.retrievedFields+=v.fields.length,t.retrievedKeyValues+=v.kv.length,t.retrievedResourceDataBytes+=((d=v.data)==null?void 0:d.length)??0;for(const R of v.kv)t.retrievedKeyValueBytes+=R.value.length}u.push(v)}}return t&&(t.millisSpent+=Date.now()-r,t.roundTrips+=h),u}function X(o){return o}function Z(o,e,t){var i;const r=o instanceof S?g.notEmpty(t).accessor(o).node():o instanceof T?o.node():o,n={...r.resourceInfo};if(e.data!==void 0&&(e.data==="raw"?n.data=r.getData():n.data=e.data.parse(r.getDataAsJson())),e.fields!==void 0){const s={};for(const[f,h]of Object.entries(e.fields))s[f]=(i=r.traverse({field:f,errorIfFieldNotSet:h,stableIfNotFound:!h}))==null?void 0:i.id;n.fields=s}if(e.kv!==void 0){const s={};for(const[f,h]of Object.entries(e.kv)){const l=r.getKeyValue(f);if(l===void 0)throw new Error(`Key not found ${f}`);h==="raw"?s[f]=l:s[f]=h.parse(JSON.parse(Buffer.from(l).toString("utf-8")))}n.kv=s}return n}function ee(o,e,t){if(o instanceof S){const r=t.accessor(o).node(),a=r.resourceInfo,n=e.map(i=>{var s,f;return[i,(f=(s=r.getField(i))==null?void 0:s.value)==null?void 0:f.id]});return{...a,fields:new Map(n),data:r.getData()??new Uint8Array}}return o}function te(o,e,t){if(!(o instanceof S))return o;const r=t.accessor(o).node(),a=r.resourceInfo,n=e.map(i=>[i,r.getKeyValue(i)]);return{...a,metadata:Object.fromEntries(n)}}class L{constructor(e,t,r,a){c(this,"finalPredicate");c(this,"state");c(this,"pollingInterval");c(this,"pruning");c(this,"logStat");c(this,"hooks");c(this,"abortController",new AbortController);c(this,"currentLoopDelayInterrupt");c(this,"scheduledOnNextState",[]);c(this,"keepRunning",!1);c(this,"currentLoop");c(this,"terminated",!1);this.pl=e,this.root=t,this.logger=a;const{finalPredicateOverride:n,pruning:i,pollingInterval:s,stopPollingDelay:f,logStat:h}=r;this.pruning=i,this.pollingInterval=s,this.finalPredicate=n??e.finalPredicate,this.logStat=h,this.state=new D(t,this.finalPredicate),this.hooks=new k.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:f},(l,m)=>this.scheduleOnNextState(l,m))}accessor(e=this.root){if(this.terminated)throw new Error("tree synchronization is terminated");return this.entry(e)}entry(e=this.root){if(this.terminated)throw new Error("tree synchronization is terminated");return new S({treeProvider:()=>this.state,hooks:this.hooks},e)}async refreshState(){if(this.terminated)throw new Error("tree synchronization is terminated");await this.hooks.refreshState()}scheduleOnNextState(e,t){this.terminated?t(new Error("tree synchronization is terminated")):(this.scheduledOnNextState.push({resolve:e,reject:t}),this.currentLoopDelayInterrupt&&(this.currentLoopDelayInterrupt.abort(),this.currentLoopDelayInterrupt=void 0))}startUpdating(){this.terminated||(this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop()))}stopUpdating(){this.keepRunning=!1}async refresh(e,t){if(this.terminated)throw new Error("tree synchronization is terminated");const r=O(this.state,this.pruning),a=await this.pl.withReadTx("ReadingTree",async n=>await x(n,r,e),t);this.state.updateFromResourceData(a,!0)}async mainLoop(){var r,a;let e=this.logStat?C():void 0,t=Date.now();for(;!(!this.keepRunning||this.terminated);){let n;this.scheduledOnNextState.length>0&&(n=this.scheduledOnNextState,this.scheduledOnNextState=[]);try{if(this.logStat==="per-request"&&(e=C()),await this.refresh(e),e&&this.logger&&this.logger.info(`Tree stat (success, after ${Date.now()-t}ms): ${JSON.stringify(e)}`),t=Date.now(),n!==void 0)for(const i of n)i.resolve()}catch(i){if(e&&this.logger&&this.logger.info(`Tree stat (error, after ${Date.now()-t}ms): ${JSON.stringify(e)}`),t=Date.now(),n!==void 0)for(const s of n)s.reject(i);if(i instanceof w){(r=this.logger)==null||r.error(i),this.state.invalidateTree("stat update error"),this.state=new D(this.root,this.finalPredicate);continue}else(a=this.logger)==null||a.warn(i)}if(!this.keepRunning||this.terminated)break;if(this.scheduledOnNextState.length===0)try{this.currentLoopDelayInterrupt=new AbortController,await q.setTimeout(this.pollingInterval,AbortSignal.any([this.abortController.signal,this.currentLoopDelayInterrupt.signal]))}catch(i){if(!p.isTimeoutOrCancelError(i))throw new Error("Unexpected error",{cause:i});break}finally{this.currentLoopDelayInterrupt=void 0}}this.currentLoop=void 0}dumpState(){return this.state.dumpState()}async terminate(){this.keepRunning=!1,this.terminated=!0,this.abortController.abort(),this.currentLoop!==void 0&&(await this.currentLoop,this.state.invalidateTree("synchronization terminated for the tree"))}async awaitSyncLoopTermination(){this.currentLoop!==void 0&&await this.currentLoop}static async init(e,t,r,a){const n=new L(e,t,r,a),i=r.logStat?C():void 0;let s=!1;try{await n.refresh(i,{timeout:r.initialTreeLoadingTimeout}),s=!0}finally{i&&a&&a.info(`Tree stat (initial load, ${s?"success":"failure"}): ${JSON.stringify(i)}`)}return n}}function re(o){var t;const e={total:{count:0,fieldNameBytes:0,fieldsCount:0,dataBytes:0,kvCount:0,kvBytes:0},byResourceType:{}};for(const r of o){const a=`${r.type.name}/${r.type.version}`;e.byResourceType[a]||(e.byResourceType[a]={count:0,fieldNameBytes:0,fieldsCount:0,dataBytes:0,kvCount:0,kvBytes:0});const n=e.byResourceType[a];n.count++,e.total.count++;for(const i of r.fields)n.fieldNameBytes+=i.name.length,n.fieldsCount++,e.total.fieldNameBytes+=i.name.length,e.total.fieldsCount++;if(r.data){const i=((t=r.data)==null?void 0:t.length)??0;n.dataBytes+=i,e.total.dataBytes+=i}n.kvCount+=r.kv.length,e.total.kvCount+=r.kv.length;for(const i of r.kv){const s=i.key.length+i.value.length;n.kvBytes+=s,e.total.kvBytes+=s}}return e}exports.PlError=z;exports.PlTreeEntry=S;exports.PlTreeEntryAccessor=T;exports.PlTreeNodeAccessor=P;exports.PlTreeResource=$;exports.PlTreeState=D;exports.SynchronizedTreeState=L;exports.TreeStateUpdateError=w;exports.constructTreeLoadingRequest=O;exports.formatTreeLoadingStat=Q;exports.initialTreeLoadingStat=C;exports.isPlTreeEntry=j;exports.isPlTreeEntryAccessor=H;exports.isPlTreeNodeAccessor=Y;exports.loadTreeState=x;exports.makeResourceSnapshot=Z;exports.mapValueAndError=I;exports.mapValueAndErrorIfDefined=J;exports.rsSchema=X;exports.treeDumpStats=re;exports.treeEntryToResourceInfo=G;exports.treeEntryToResourceWithData=ee;exports.treeEntryToResourceWithMetadata=te;
|
|
11
11
|
//# sourceMappingURL=index.js.map
|