@prisma/extension-optimize 0.0.0-dev.202408261452 → 0.0.0-dev.202408261524

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.d.ts CHANGED
@@ -9,29 +9,40 @@ type OptimizeOptions = {
9
9
  */
10
10
  enable?: boolean;
11
11
  /**
12
- * The URL of the ingestion service of Prisma Optimize.
12
+ * A Prisma Optimize API token. Head to the Prisma Optimize dashboard to
13
+ * create one.
13
14
  */
14
- ingestionUrl?: string;
15
+ token: string;
15
16
  /**
16
- * The URL of the dashboard of Prisma Optimize
17
+ * The minimum interval (in milliseconds) for sending batched Prisma
18
+ * operations to the Prisma Optimize interface.
19
+ *
20
+ * @default 500
21
+ * @remarks setting this value too low may impact your app performance.
17
22
  */
18
- dashboardUrl?: string;
23
+ sendInterval?: number;
19
24
  /**
20
- * A Prisma Optimize API token. Head to the Prisma Optimize dashboard to
21
- * create one.
25
+ * The maximum time a query can be waited for before being discarded. If a
26
+ * query takes too long to complete, it will be discarded. Increase this if
27
+ * you have very slow queries.
28
+ *
29
+ * @default 10000
30
+ * @remarks when below `minSendInterval`, it defaults to `minSendInterval`.
22
31
  */
23
- token: string;
32
+ sendTimeout?: number;
33
+ /**
34
+ * The URL of the ingestion service of Prisma Optimize.
35
+ */
36
+ ingestionUrl?: string;
24
37
  /**
25
- * The minimum interval in milliseconds between sending batched requests to the ingestion service.
26
- * This is only currently used when tracing is enabled. When tracing is disabled, the requests
27
- * are not batched, and are sent immediately on the next event loop tick.
38
+ * The URL of the dashboard of Prisma Optimize
28
39
  */
29
- minSendInterval?: number;
40
+ dashboardUrl?: string;
30
41
  /**
31
- * Whether to show a CLI notification when the dashboard is ready.
42
+ * Whether to show a toast notification when the dashboard is ready.
32
43
  */
33
44
  showNotification?: boolean;
34
45
  };
35
- declare function withOptimize({ enable, ingestionUrl, dashboardUrl, minSendInterval, showNotification, token, }: OptimizeOptions): (client: any) => _prisma_client_extension.PrismaClientExtends<_prisma_client_runtime_library.InternalArgs<{}, {}, {}, {}> & _prisma_client_runtime_library.DefaultArgs>;
46
+ declare function withOptimize({ enable, ingestionUrl, dashboardUrl, sendInterval, sendTimeout, showNotification, token, }: OptimizeOptions): (client: any) => _prisma_client_extension.PrismaClientExtends<_prisma_client_runtime_library.InternalArgs<{}, {}, {}, {}> & _prisma_client_runtime_library.DefaultArgs>;
36
47
 
37
48
  export { type OptimizeOptions, PROD_DASHBOARD_URL, PROD_INGESTION_URL, withOptimize };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var X=Object.create;var l=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var ee=Object.getOwnPropertyNames;var te=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty;var se=(n,e)=>{for(var t in e)l(n,t,{get:e[t],enumerable:!0})},x=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ee(e))!ne.call(n,i)&&i!==t&&l(n,i,{get:()=>e[i],enumerable:!(s=Y(e,i))||s.enumerable});return n};var C=(n,e,t)=>(t=n!=null?X(te(n)):{},x(e||!n||!n.__esModule?l(t,"default",{value:n,enumerable:!0}):t,n)),ie=n=>x(l({},"__esModule",{value:!0}),n);var ce={};se(ce,{PROD_DASHBOARD_URL:()=>G,PROD_INGESTION_URL:()=>V,withOptimize:()=>de});module.exports=ie(ce);var Q=require("@opentelemetry/api"),B=require("@prisma/client/extension"),J=C(require("@prisma/debug"));function re(n,e){let t;return async function(s,i,r){let p=new URL(s,n),d=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});t&&d.set("prisma-optimize-jwt",t);let o=await fetch(p,{method:i,headers:d,body:JSON.stringify(r)});if(!o.ok){let a=await o.text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${o.status} ${o.statusText}: ${a}`)}let m=o.headers.get("prisma-optimize-jwt");return m&&(t=m),o}}function b(n,e){let t=re(n,e);return{request:t,post:(s,i)=>t(s,"POST",i)}}async function P(n,e){return await(await n.post("/schema",{schema:e})).text()}var q=C(require("kleur"));var{bold:oe,underline:ae}=q.default;function v(n){let e="See your Optimize dashboard at:",t=e.length,s=`${ae(oe(n))}`,i=n.length,r=Math.max(t,i)+2;console.log("\u250C"+"\u2500".repeat(r)+"\u2510"),console.log("\u2502 "+e+" ".repeat(r-t-2)+" \u2502"),console.log("\u2502 "+s+" ".repeat(r-i-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(r)+"\u2518")}var O=require("@opentelemetry/api"),k=require("@opentelemetry/context-async-hooks"),M=require("@opentelemetry/instrumentation"),F=require("@opentelemetry/resources"),z=require("@opentelemetry/sdk-trace-base"),g=require("@opentelemetry/semantic-conventions"),N=require("@prisma/instrumentation");var A=C(require("@prisma/debug"));async function E(n,e){await n.post("/ingest",e)}function I(n,...e){setTimeout(()=>{n(...e)},0)}function c(n){return n[0]*1e3+n[1]/1e6}var h=(0,A.default)("prisma:extension:optimize"),u="0000000000000000",_=(r=>(r.ClientOperation="prisma:client:operation",r.ClientConnect="prisma:client:connect",r.Engine="prisma:engine",r.EngineConnection="prisma:engine:connection",r.EngineQuery="prisma:engine:db_query",r))(_||{}),y=class{spanId;timestamp;model;operation;args;statementSpans;duration;connect;error;completionFlags={clientSpanClosed:!1,engineSpanClosed:!1};constructor(e){this.spanId=e.spanId,this.timestamp=e.timestamp,this.model=e.model,this.operation=e.operation,this.args=e.args,this.statementSpans=[]}isCompleted(){return this.completionFlags.clientSpanClosed&&this.completionFlags.engineSpanClosed}statementSpansToString(){return this.statementSpans.sort((t,s)=>{let i=c(t.startTime),r=c(s.startTime);return i-r}).reduce((t,s)=>{let i=s.attributes["db.statement"];return typeof i=="string"?`${t}${i}
2
- `:(h("sql attribute is not a string: %o",i),t)},"")}toIngestRequestItem(e){if(this.duration===void 0)throw new Error("`duration` is `undefined`, this should not happen");return{ts:this.timestamp,model:this.model??null,operation:this.operation,args:this.args,latency:this.duration,connect:this.connect??!1,sql:this.statementSpansToString(),error:this.error??null,hash:e}}},f=class{#t=new Map;#n=new Map;#s=new Map;#o=new Set;#e=[];#a=Promise.resolve();#p=!1;#c;#m;#i=new Set;#l=Promise.resolve();#d=!1;#u;setSchemaHash=()=>{};__test_internalMetrics__={rescheduledCountTotal:0};constructor(e,t){this.#c=e,this.#m=t,this.#u=new Promise(s=>{this.setSchemaHash=s})}createRequest(e){let t=new y(e);this.#t.set(e.spanId,t)}setRequestError(e,t){let s=this.#t.get(e);if(!s)throw new Error(`Unknown request ${e}`);s.error=t}#S(e){for(let t=e;t!==u;t=this.#n.get(t)){if(t===void 0)return{type:"UndeliveredSpanInTree"};let s=this.#t.get(t);if(s)return{type:"Ok",request:s}}return{type:"NotInRequestTree"}}onStart(e,t){if(!T(e))return;let s=e.spanContext().spanId;if(!e.parentSpanId){this.#n.set(s,u);return}if(this.#n.set(s,e.parentSpanId),e.parentSpanId===u)return;let i=this.#s.get(e.parentSpanId);i?i.add(s):this.#s.set(e.parentSpanId,new Set([s])),e.name==="prisma:engine:connection"&&this.#o.add(s)}onEnd(e){T(e)?this.#h(e):(e.parentSpanId===void 0||e.parentSpanId===u)&&this.#r(e.spanContext().spanId)}async forceFlush(){await this.#a,await this.#g()}async shutdown(){await this.forceFlush()}#h(e){let t=e.spanContext().spanId,s,i=this.#S(t);switch(i.type){case"Ok":s=i.request;break;case"UndeliveredSpanInTree":this.#C(e);break;case"NotInRequestTree":this.#r(t);break}s&&(e.name==="prisma:client:connect"&&(s.connect=c(e.duration)),e.name==="prisma:engine"&&(s.completionFlags.engineSpanClosed=!0),e.name==="prisma:engine:db_query"&&!this.#o.has(e.parentSpanId)&&s.statementSpans.push(e),e.name==="prisma:client:operation"&&(s.duration=c(e.duration),s.completionFlags.clientSpanClosed=!0,h("latency otel: %d",s.duration)),s.isCompleted()&&this.#w(s))}#C(e){this.#e.push(e),this.__test_internalMetrics__.rescheduledCountTotal++;let{spanId:t,traceId:s}=e.spanContext();h("rescheduled ",e.name,t,e.parentSpanId,s),!this.#p&&(this.#p=!0,this.#a=Promise.all([this.#a,new Promise(I).then(()=>this.#I())]))}#I(){let e=this.#e;this.#e=[],this.#p=!1;for(let t of e)this.#h(t)}#r(e){this.#n.delete(e),this.#o.delete(e);let t=this.#s.get(e);if(this.#s.delete(e),this.#y(e),t)for(let s of t)this.#r(s)}#y(e){for(let t=this.#f(e);t!==-1;t=this.#f(e))this.#e.splice(t,1)}#f(e){return this.#e.findIndex(t=>t.spanContext().spanId===e)}#w(e){I(()=>{this.#t.delete(e.spanId),this.#r(e.spanId),this.#i.add(e),this.#R()})}async#R(){await this.#l,!this.#d&&(this.#d=!0,setTimeout(()=>{this.#l=this.#g().finally(()=>{this.#d=!1})},this.#m))}async#g(){if(this.#i.size===0)return;let e=await this.#u,t=[...this.#i].map(s=>s.toIngestRequestItem(e));this.#i.clear(),h("sending batch of %d requests",t.length);try{await E(this.#c,t)}catch(s){console.error(s.message??s)}}};function T(n){return Object.values(_).includes(n.name)}function j(n,e){let t=new k.AsyncHooksContextManager().enable();O.context.setGlobalContextManager(t);let s=new z.BasicTracerProvider({resource:new F.Resource({[g.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[g.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})}),i=new f(n,e);return s.addSpanProcessor(i),(0,M.registerInstrumentations)({tracerProvider:s,instrumentations:[new N.PrismaInstrumentation]}),s.register(),i}function L(n){return n._previewFeatures?.includes("tracing")}function U(n){return n._engineConfig.inlineSchema}function $(n){if(n instanceof Error)return n.stack??n.message;switch(typeof n){case"undefined":return"undefined";case"object":{let e;return n!==null&&typeof n.toString=="function"&&(e=n.toString()),typeof e=="string"&&e!=="[object Object]"?e:JSON.stringify(n)}default:return String(n)}}var H=require("@prisma/client/extension"),D=H.Prisma.defineExtension(n=>n.$extends({}));var V="https://optimize-ingestion.datacdn.workers.dev/",G="https://optimize.prisma.io",pe=(0,J.default)("prisma:extension:optimize");function de({enable:n=!0,ingestionUrl:e=V,dashboardUrl:t=G,minSendInterval:s=50,showNotification:i=!0,token:r}){return n?(i&&v(t),B.Prisma.defineExtension(p=>{let d=b(e,r),o=j(d,s);if(!L(p))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');let m=U(p);return P(d,m).then(a=>{pe("uploaded schema with hash",a),o.setSchemaHash(a)},a=>{console.error(a),console.error("Failed to upload the schema, no data will be sent to Prisma Optimize")}),p.$extends({query:{async $allOperations({query:a,model:Z,operation:K,args:w}){let S=Q.trace.getActiveSpan()?.spanContext().spanId;if(!S)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");o.createRequest({spanId:S,timestamp:Date.now(),model:Z,operation:K,args:w});try{return await a(w)}catch(R){let W=$(R);throw o.setRequestError(S,W),R}}}})})):D}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
1
+ "use strict";var K=Object.create;var S=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var te=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},C=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of X(e))!ee.call(t,r)&&r!==n&&S(t,r,{get:()=>e[r],enumerable:!(s=W(e,r))||s.enumerable});return t};var ne=(t,e,n)=>(n=t!=null?K(Y(t)):{},C(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),re=t=>C(S({},"__esModule",{value:!0}),t);var ue={};te(ue,{PROD_DASHBOARD_URL:()=>Q,PROD_INGESTION_URL:()=>J,withOptimize:()=>de});module.exports=re(ue);var N=require("@opentelemetry/api"),D=require("@prisma/client/extension");function se(t,e){let n;return async function(s,r,o){let a=new URL(s,t),m=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});n&&m.set("prisma-optimize-jwt",n);let p=await fetch(a,{method:r,headers:m,body:JSON.stringify(o)});if(!p.ok){let h=await p.text().catch(()=>"<unreadable>");console.error(`[optimize] HTTP ${p.status} ${p.statusText}: ${h}`)}let u=p.headers.get("prisma-optimize-jwt");return u&&(n=u),p}}function w(t,e){let n=se(t,e);return{request:n,post:(s,r)=>n(s,"POST",r)}}var v=ne(require("kleur"));var{bold:ie,underline:oe}=v.default;function R(t){let e="See your Optimize dashboard at:",n=e.length,s=`${oe(ie(t))}`,r=t.length,o=Math.max(n,r)+2;console.log("\u250C"+"\u2500".repeat(o)+"\u2510"),console.log("\u2502 "+e+" ".repeat(o-n-2)+" \u2502"),console.log("\u2502 "+s+" ".repeat(o-r-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(o)+"\u2518")}var q=require("@opentelemetry/api"),O=require("@opentelemetry/context-async-hooks"),j=require("@opentelemetry/instrumentation"),_=require("@opentelemetry/resources"),z=require("@opentelemetry/sdk-trace-base"),b=require("@opentelemetry/semantic-conventions"),k=require("@prisma/instrumentation");var i=require("zod");async function P(t,e){e.length>0&&await t.post("/ingest",e)}async function E(t,e){return await(await t.post("/schema",{schema:e})).text()}function c(t){return t[0]*1e3+t[1]/1e6}var l=require("zod"),f=class{spans={};rootSpans={};waitSpans={};treeShape;collectedSpans;collectedRootSpans;sendTimeout;sendInterval;pendingSend;constructor(e){this.treeShape=e.treeShape,this.sendTimeout=e.sendTimeout,this.sendInterval=e.sendInterval,this.collectedSpans=e.collectedSpans,this.collectedRootSpans=e.collectedRootSpans,this.onEnd=ae(()=>void this.forceFlush(),this.sendInterval)}onStart(e){let{parentSpanId:n,name:s}=e,{spanId:r}=e.spanContext();if(!this.collectedSpans.includes(s))return this.cleanSpan(this.spans[r]);this.spans[r]&&this.spans[r].kind==="future"?Object.assign(this.spans[r],{kind:"present",value:e}):this.spans[r]={spanId:r,kind:"present",children:[],value:e,retries:0},this.collectedRootSpans.includes(s)&&(this.rootSpans[r]=this.spans[r],this.waitSpans[r]=this.spans[r]),n!==void 0&&(this.spans[n]?this.spans[n].children.push(this.spans[r]):(this.spans[n]={spanId:n,kind:"future",children:[this.spans[r]],retries:0},this.waitSpans[n]=this.spans[n]))}cleanSpan(e){if(e===void 0)return;let n=e.spanId;for(let s of e.children)this.cleanSpan(s);delete this.spans[n],delete this.rootSpans[n],delete this.waitSpans[n],this.onClean(e)}async forceFlush(){await this.pendingSend;let e=Object.values(this.rootSpans).flatMap(n=>{let{data:s}=this.treeShape.safeParse(n);return s?[{original:n,pruned:s}]:[]});e.length>0&&(this.pendingSend=this.onFlush(e).finally(()=>{e.forEach(({original:n})=>this.cleanSpan(n))}));for(let n of Object.values(this.waitSpans))++n.retries*this.sendInterval>this.sendTimeout&&this.cleanSpan(n)}async shutdown(){await this.forceFlush(),this.spans={},this.rootSpans={},this.waitSpans={}}onEnd(){}};function ae(t,e){let n=!1;return()=>{n===!1&&(n=!0,setTimeout(()=>(n=!1)||t(),e))}}var d={ended:l.z.literal(!0),_spanContext:l.z.custom(),spanContext:l.z.custom(),startTime:l.z.custom(),endTime:l.z.custom(),attributes:l.z.custom()};var pe=i.z.object({value:i.z.object({name:i.z.literal("prisma:engine:db_query"),...d})}),y=i.z.object({value:i.z.object({name:i.z.literal("prisma:engine"),...d}),children:i.z.array(pe).nonempty()}),A=i.z.object({value:i.z.object({name:i.z.literal("prisma:client:connect"),...d})}),ce=i.z.object({value:i.z.object({name:i.z.literal("prisma:client:operation"),...d}),children:i.z.union([i.z.tuple([y]),i.z.tuple([A,y]),i.z.tuple([y,A])])}),g=class extends f{requests={};errors={};schemaHash;apiClient;constructor(e){super({treeShape:ce,sendTimeout:e.sendTimeout,sendInterval:e.sendInterval,collectedSpans:["prisma:client:operation","prisma:client:connect","prisma:engine","prisma:engine:db_query"],collectedRootSpans:["prisma:client:operation"]}),this.apiClient=e.apiClient,this.schemaHash=E(this.apiClient,e.schema)}setRequest(e){this.requests[e.spanId]=e}setError(e){this.errors[e.spanId]=e}onClean({spanId:e}){delete this.requests[e],delete this.errors[e]}async onFlush(e){let n=await this.schemaHash,s=[];for(let{pruned:r}of e){let{value:o}=r,a=o.spanContext().spanId;this.requests[a]&&s.push({hash:n,sql:le(r),ts:c(o.startTime),connect:me(r),error:this.errors[a]?.error??null,model:this.requests[a].model??null,operation:this.requests[a].operation,args:this.requests[a].args??{},latency:c(o.endTime)-c(o.startTime)})}await P(this.apiClient,s)}};function le(t){return t.children.find(({value:r})=>r.name==="prisma:engine").children.filter(({value:r})=>r.name==="prisma:engine:db_query").sort((r,o)=>c(r.value.startTime)-c(o.value.startTime)).reduce((r,o)=>{let a=o.value.attributes["db.statement"];return typeof a=="string"?`${r}${a}
2
+ `:r},"")}function me(t){let{value:e}=t.children.find(({value:n})=>n.name==="prisma:client:connect")??{};return e?c(e.endTime)-c(e.startTime):!1}function F(t){let e=new O.AsyncHooksContextManager().enable();q.context.setGlobalContextManager(e);let n=new z.BasicTracerProvider({resource:new _.Resource({[b.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[b.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})}),s=new g(t);return n.addSpanProcessor(s),(0,j.registerInstrumentations)({tracerProvider:n,instrumentations:[new k.PrismaInstrumentation]}),n.register(),s}function M(t){return t._previewFeatures?.includes("tracing")}function H(t){return t._engineConfig.inlineSchema}function L(t){if(t instanceof Error)return t.stack??t.message;switch(typeof t){case"undefined":return"undefined";case"object":{let e;return t!==null&&typeof t.toString=="function"&&(e=t.toString()),typeof e=="string"&&e!=="[object Object]"?e:JSON.stringify(t)}default:return String(t)}}var $=require("@prisma/client/extension"),U=$.Prisma.defineExtension(t=>t.$extends({}));var J="https://optimize-ingestion.datacdn.workers.dev/",Q="https://optimize.prisma.io";function de({enable:t=!0,ingestionUrl:e=J,dashboardUrl:n=Q,sendInterval:s=500,sendTimeout:r=1e4,showNotification:o=!0,token:a}){return t?(o&&R(n),D.Prisma.defineExtension(m=>{let p=H(m),u=w(e,a),h=F({schema:p,apiClient:u,sendInterval:s,sendTimeout:r});if(!M(m))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return m.$extends({query:{async $allOperations({query:V,model:B,operation:G,args:x}){let T=N.trace.getActiveSpan()?.spanContext().spanId;if(!T)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");h.setRequest({spanId:T,model:B,operation:G,args:x});try{return await V(x)}catch(I){let Z=L(I);throw h.setError({spanId:T,error:Z}),I}}}})})):U}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/extension-optimize",
3
- "version": "0.0.0-dev.202408261452",
3
+ "version": "0.0.0-dev.202408261524",
4
4
  "sideEffects": false,
5
5
  "description": "",
6
6
  "main": "./dist/index.js",
@@ -8,16 +8,16 @@
8
8
  "keywords": [],
9
9
  "dependencies": {
10
10
  "@opentelemetry/api": "^1.8",
11
- "@opentelemetry/instrumentation": "^0.49 || ^0.50 || ^0.51",
12
- "@opentelemetry/sdk-trace-base": "^1.22",
13
11
  "@opentelemetry/context-async-hooks": "1.22.0",
14
12
  "@opentelemetry/exporter-trace-otlp-http": "0.49.1",
13
+ "@opentelemetry/instrumentation": "^0.49 || ^0.50 || ^0.51",
15
14
  "@opentelemetry/resources": "1.22.0",
15
+ "@opentelemetry/sdk-trace-base": "^1.22",
16
16
  "@opentelemetry/semantic-conventions": "1.22.0",
17
17
  "@prisma/debug": "5.12.1",
18
18
  "@prisma/instrumentation": "5.18.0",
19
19
  "kleur": "4.1.5",
20
- "readline-sync": "1.4.10"
20
+ "zod": "3.23.8"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@hono/node-server": "1.9.1",
@@ -26,7 +26,7 @@
26
26
  "hono": "4.4.6",
27
27
  "tsup": "8.0.2",
28
28
  "vitest": "1.4.0",
29
- "common": "0.0.0-dev.202408261452"
29
+ "common": "0.0.0-dev.202408261524"
30
30
  },
31
31
  "peerDependencies": {
32
32
  "@prisma/client": "5.x"