import{PLAN_GATES_DEFAULTS as g}from"../../../constants/entitlements.js";import{EntitlementsProvider as m}from"../../../entitlements/entitlements-provider.js";import{BaseService as S}from"../../../providers/database/base-service.js";import{InstanceCacheResolver as f}from"../../../providers/database/instance-cache-resolver.js";import{StorageLimitValidator as h}from"../../../providers/database/utils/storage-limit-validator.js";import{KvRepository as p}from"../repositories/kv-repository.js";import{encodeKvKey as E}from"../mappers/create-kv-db-record.js";import{kvKeyValidator as i,kvListOptionsValidator as B,kvListSelectorValidator as w,kvSetOptionsValidator as d}from"../schemas/kv-schemas.js";const k=100*1024*1024;class l extends S{static#n=new f(async t=>new l(await p.create(t),t));#t;constructor(t,e){super(e,{repository:t,createRepository:p.create}),this.#t=new h}static async getInstance(t){return l.#n.get(t)}async get(t){const e=i.parse(t);return this.runRead(r=>r.get(e))}async getMany(t){if(t.length===0)return[];const e=t.map(r=>i.parse(r));return this.runRead(r=>r.getMany(e))}async list(t,e){const r=w.parse(t),s=B.parse(e??{});return this.runRead(n=>n.list(r,s))}async set(t,e,r){const s=i.parse(t),n=d.parse(r??{});this.#e(e);const a=JSON.stringify(e);return this.#r(a),await this.#s(s,a),this.runWrite(o=>o.set(s,e,n))}async delete(t){const e=i.parse(t);await this.runWrite(r=>r.delete(e))}async clearExpired(){await this.runWrite(t=>t.clearExpired())}async transaction(t){return await this.syncRepositoryIfNeeded(),this.getRepository().transaction(async e=>t({get:async s=>{const n=i.parse(s);return e.get(n)},getMany:async s=>{const n=s.map(a=>i.parse(a));return e.getMany(n)},set:async(s,n,a)=>{const o=i.parse(s),c=d.parse(a??{});this.#e(n);const y=JSON.stringify(n);return this.#r(y),await this.#s(o,y,{skipSync:!0}),e.set(o,n,c)},delete:async s=>{const n=i.parse(s);return e.delete(n)}}))}#e(t){try{JSON.stringify(t)}catch(e){const r=e instanceof Error?e.message:"Unknown error";throw new Error(`Value is not JSON serializable: ${r}`)}}#r(t){const r=Buffer.byteLength(t,"utf8");if(r>1048576){const s=(r/1024).toFixed(2);throw new Error(`Value size (${s} KB) exceeds the maximum allowed size of 1 MB (1024 KB)`)}}async#s(t,e,r){const s=E(t),n=await this.runRead(async c=>{const y=await c.getTotalStoredEntryBytes(),u=await c.getStoredEntrySizeByEncodedKey(s);return{currentTotalStoredEntryBytes:y,existingEntryBytes:u}},{onRepositoryMissing:()=>null,skipSync:r?.skipSync??!1});if(!n)return;const a=Math.max(0,n.currentTotalStoredEntryBytes-k),o=Buffer.byteLength(s,"utf8")+Buffer.byteLength(e,"utf8");this.#t.validate({storageLimitGb:this.#a(),currentTotalBytes:a,existingEntryBytes:n.existingEntryBytes,incomingEntryBytes:o,errorMessagePrefix:"KV storage limit"})}#a(){const t=m.instance().entitlements?.kvStorageLimit;return typeof t=="number"&&t>0?t:g.pro.kvStorageLimit}}export{l as KvService};
