@prisma/extension-optimize 0.5.3 → 0.6.0
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/README.md +25 -10
- package/dist/index.d.ts +2 -4
- package/dist/index.js +3 -3
- package/package.json +6 -4
package/README.md
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
# Optimize Prisma Client extension
|
|
2
2
|
|
|
3
|
-
This is the package for the [Prisma Client extension](https://www.prisma.io/docs/concepts/components/prisma-client/client-extensions?utm_source=github&utm_medium=
|
|
3
|
+
This is the package for the [Prisma Client extension](https://www.prisma.io/docs/concepts/components/prisma-client/client-extensions?utm_source=github&utm_medium=optimize-readme) that enables usage of Prisma Optimize.
|
|
4
4
|
|
|
5
|
-
Optimize enables developers to profile and get performance-related recommendations while developing applications with
|
|
5
|
+
Optimize enables developers to profile and get performance-related recommendations while developing applications with Prisma.
|
|
6
6
|
|
|
7
|
-
It is part of the [Prisma](https://www.prisma.io?utm_source=github&utm_medium=
|
|
7
|
+
It is part of the [Prisma](https://www.prisma.io?utm_source=github&utm_medium=optimize-readme) ecosystem, alongside other tools such as:
|
|
8
8
|
|
|
9
|
-
- [Prisma Accelerate](https://www.prisma.io/data-platform/accelerate?utm_source=github&utm_medium=
|
|
10
|
-
- [Prisma Pulse](https://www.prisma.io/data-platform/pulse?utm_source=github&utm_medium=
|
|
9
|
+
- [Prisma Accelerate](https://www.prisma.io/data-platform/accelerate?utm_source=github&utm_medium=optimize-readme): Global database cache with scalable connection pooling.
|
|
10
|
+
- [Prisma Pulse](https://www.prisma.io/data-platform/pulse?utm_source=github&utm_medium=optimize-readme): Real-time database events with type-safe subscriptions.
|
|
11
11
|
|
|
12
|
-
Prisma is leading Data DX, a philosophy that promotes simplicity in data-driven application development. Learn more on the [Data DX manifesto](https://www.datadx.io/?utm_source=github&utm_medium=
|
|
12
|
+
Prisma is leading Data DX, a philosophy that promotes simplicity in data-driven application development. Learn more on the [Data DX manifesto](https://www.datadx.io/?utm_source=github&utm_medium=optimize-readme).
|
|
13
13
|
|
|
14
14
|
## Getting started with Optimize
|
|
15
15
|
|
|
@@ -21,20 +21,35 @@ Enabling Optimize in your local development workflow is really simple.
|
|
|
21
21
|
npm install @prisma/extension-optimize --save-dev
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
> Starting a
|
|
24
|
+
> Starting a Prisma project from scratch? Follow https://www.prisma.io/docs/getting-started
|
|
25
25
|
|
|
26
|
-
### 2.
|
|
26
|
+
### 2. Enable the `tracing` preview feature in your schema
|
|
27
27
|
|
|
28
|
+
```diff
|
|
29
|
+
generator client {
|
|
30
|
+
provider = "prisma-client-js"
|
|
31
|
+
+ previewFeatures = ["tracing"]
|
|
32
|
+
}
|
|
28
33
|
```
|
|
34
|
+
|
|
35
|
+
After enabling the `tracing` preview feature, you need to re-generate your Prisma Client:
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
npx prisma generate
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### 3. Extend your Prisma Client with Optimize support
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
29
44
|
import { PrismaClient } from "@prisma/client";
|
|
30
45
|
import { withOptimize } from "@prisma/extension-optimize";
|
|
31
46
|
|
|
32
47
|
const prisma = new PrismaClient().$extends(withOptimize());
|
|
33
48
|
```
|
|
34
49
|
|
|
35
|
-
The extension will orchestrate the user experience around
|
|
50
|
+
The extension will orchestrate the user experience around Optimize. You will:
|
|
36
51
|
|
|
37
|
-
- Be required to log into the
|
|
52
|
+
- Be required to log into the Prisma Data Platform through your GitHub account
|
|
38
53
|
- And be instructed to visit the URL of your Optimize dashboard:
|
|
39
54
|
|
|
40
55
|
```
|
package/dist/index.d.ts
CHANGED
|
@@ -17,10 +17,8 @@ type OptimizeOptions = {
|
|
|
17
17
|
*/
|
|
18
18
|
dashboardUrl?: string;
|
|
19
19
|
/**
|
|
20
|
-
* Whether to use tracing or not.
|
|
21
|
-
*
|
|
22
|
-
* without tracing but capturing the SQL statements and detecting cold starts is only
|
|
23
|
-
* available with tracing.
|
|
20
|
+
* Whether to use tracing or not. Basic functionality is available without tracing
|
|
21
|
+
* but capturing the SQL statements and detecting cold starts is only available with tracing.
|
|
24
22
|
*/
|
|
25
23
|
useTracing?: boolean;
|
|
26
24
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ue=Object.create;var f=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var we=(t,e)=>{for(var n in e)f(t,n,{get:e[n],enumerable:!0})},z=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of he(e))!Se.call(t,o)&&o!==n&&f(t,o,{get:()=>e[o],enumerable:!(r=fe(e,o))||r.enumerable});return t};var a=(t,e,n)=>(n=t!=null?ue(ge(t)):{},z(e||!t||!t.__esModule?f(n,"default",{value:t,enumerable:!0}):n,t)),ye=t=>z(f({},"__esModule",{value:!0}),t);var Oe={};we(Oe,{PROD_DASHBOARD_URL:()=>ce,PROD_INGESTION_URL:()=>me,withOptimize:()=>Ae});module.exports=ye(Oe);var se=require("@opentelemetry/api"),ae=require("@prisma/client/extension"),pe=a(require("@prisma/debug")),le=a(require("kleur")),de=a(require("readline-sync"));var I;async function h(t,e,n){let r=new URL("/ingest",t),o=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});I&&o.set("prisma-optimize-jwt",I);let s=await fetch(r,{method:"POST",headers:o,body:JSON.stringify(n)});if(!s.ok){console.error(`[optimize] HTTP ${s.status} ${s.statusText}: ${await s.text()}`),s.status===401&&(console.error("[optimize] Try logging out, run `pnpm prisma platform auth logout --early-access`"),console.error("[optimize] And log in again, run `pnpm prisma platform auth login --early-access`"));return}let i=s.headers.get("prisma-optimize-jwt");i&&(I=i)}var L=a(require("fs")),F=a(require("path")),M=a(require("@prisma/debug")),U=a(require("xdg-app-paths")),Re=(0,M.default)("prisma:extension:optimize"),be=new U.default("prisma-platform-cli").config(),Ie=F.default.join(be,"auth.json");function xe(t){if(typeof t!="object"||t===null)throw new Error("Invalid credentials");if(typeof t.token!="string")throw new Error("Invalid credentials");return t}function x(){try{let t=L.default.readFileSync(Ie,"utf-8");return xe(JSON.parse(t)).token}catch(t){return Re(t),null}}var _=require("child_process");function D(){let t=(0,_.spawnSync)("npx",["prisma","platform","auth","login","--early-access"],{stdio:"inherit",shell:!0});if(t.error)throw t.error}var d=a(require("fs")),N=a(require("path")),$=require("stream"),j=require("stream/promises"),J=a(require("kleur")),B=require("node-notifier"),H=a(require("xdg-app-paths")),Pe="https://avatars.githubusercontent.com/u/17219288?s=96",{bold:qe,underline:ve}=J.default;async function Te(t){let e=new H.default("prisma-optimize").config();d.default.mkdirSync(e,{recursive:!0});let n=N.default.resolve(e,"avatar.png");if(!d.default.existsSync(n)){let l=await fetch(Pe);if(l.ok&&l.body!=null){let R=d.default.createWriteStream(n,{flags:"wx"});await(0,j.finished)($.Readable.fromWeb(l.body).pipe(R))}}let r="See your Optimize dashboard at:",o=r.length,s=`${ve(qe(t))}`,i=t.length,p=Math.max(o,i)+2;console.log("\u250C"+"\u2500".repeat(p)+"\u2510"),console.log("\u2502 "+r+" ".repeat(p-o-2)+" \u2502"),console.log("\u2502 "+s+" ".repeat(p-i-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(p)+"\u2518"),(0,B.notify)({timeout:10,open:t,subtitle:"Your dashboard is ready! \u{1F680} ",message:"Click to open",title:"Prisma Optimize",icon:d.default.existsSync(n)?n:void 0,contentImage:d.default.existsSync(n)?n:void 0})}var Q={dashboardReady:Te};var W=require("@opentelemetry/api"),Y=require("@opentelemetry/context-async-hooks"),G=require("@opentelemetry/instrumentation"),X=require("@opentelemetry/resources"),Z=require("@opentelemetry/sdk-trace-base"),y=require("@opentelemetry/semantic-conventions"),K=require("@prisma/instrumentation");var V=a(require("@prisma/debug"));function g(t,...e){setTimeout(()=>{t(...e)},0)}function P(t){return t[0]*1e3+t[1]/1e6}var S=(0,V.default)("prisma:extension:optimize"),q="0000000000000000",v=class{spanId;timestamp;model;operation;args;duration;connect;sql;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}#e(){return this.completionFlags.clientSpanClosed&&this.completionFlags.engineSpanClosed}completedRequest(){if(this.#e()&&this.error!==void 0){if(this.duration===void 0)throw new Error("Invariant violation: duration cannot still be undefined after the client span is closed because it is retrieved from the client span. This is a bug.");return{ts:this.timestamp,model:this.model??null,operation:this.operation,args:this.args,latency:this.duration,connect:this.connect??!1,sql:this.sql??null,error:this.error}}}},w=class{#e=new Map;#o=Promise.resolve();#t=new Map;#n=new Map;#s;#a;#p;#r=[];#i=!1;#l=0;constructor(e,n,r){this.#s=e,this.#a=n,this.#p=r}createRequest(e){let n=new v(e);this.#e.set(e.spanId,n)}setRequestError(e,n){let r=this.#e.get(e);if(!r)throw new Error(`Unknown request ${e}`);r.error=n}#u(e){for(let n=e;n!==q;n=this.#t.get(n)){if(n===void 0)return{type:"UndeliveredSpanInTree"};let r=this.#e.get(n);if(r)return{type:"Ok",request:r}}return{type:"NotInRequestTree"}}onStart(e,n){let r=e.spanContext().spanId;if(!e.parentSpanId){this.#t.set(r,q);return}if(this.#t.set(r,e.parentSpanId),e.parentSpanId===q)return;let o=this.#n.get(e.parentSpanId);o?o.add(r):this.#n.set(e.parentSpanId,new Set([r]))}onEnd(e){this.#d(e)}async forceFlush(){await this.#o,await this.#c()}async shutdown(){await this.forceFlush()}#d(e){let n=e.spanContext().spanId,r,o=this.#u(n);switch(o.type){case"Ok":r=o.request;break;case"UndeliveredSpanInTree":this.#f(e);break;case"NotInRequestTree":this.#m(n);break}if(!r)return;switch(e.name){case"prisma:client:connect":{r.connect=P(e.duration);break}case"prisma:engine:db_query":{let i=e.attributes["db.statement"];typeof i=="string"?r.sql=i:S("db.statement in span %s must be a string, got %o",n,i),r.completionFlags.engineSpanClosed=!0;break}case"prisma:client:operation":{let i=P(e.duration);S("latency otel: %d",i),r.duration=i,r.completionFlags.clientSpanClosed=!0;break}}let s=r.completedRequest();s&&(this.#e.delete(r.spanId),this.#h(s))}#f(e){this.#o=Promise.all([this.#o,new Promise(n=>{g(()=>{this.#d(e),n()})})]).then(()=>{})}#m(e){this.#t.delete(e);let n=this.#n.get(e);if(this.#n.delete(e),n)for(let r of n)this.#m(r)}#h(e){this.#r.push(e),this.#g()}#g(){if(this.#i)return;this.#i=!0;let e=Date.now()-this.#l;S("time since last send: %d",e),setTimeout(()=>{this.#i=!1,this.#c()},Math.max(0,this.#p-e))}async#c(){if(this.#r.length===0)return;let e=this.#r;this.#r=[],S("sending batch of %d requests",e.length),this.#l=Date.now(),await h(this.#s,this.#a,e)}};function ee(t,e,n){let r=new Y.AsyncHooksContextManager().enable();W.context.setGlobalContextManager(r);let o=new Z.BasicTracerProvider({resource:new X.Resource({[y.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[y.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})}),s=new w(t,e,n);return o.addSpanProcessor(s),(0,G.registerInstrumentations)({tracerProvider:o,instrumentations:[new K.PrismaInstrumentation]}),o.register(),s}function te(t){return t._previewFeatures?.includes("tracing")}function ne(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 re=require("@prisma/client/extension"),oe=re.Prisma.defineExtension(t=>t.$extends({}));var Ce=(0,pe.default)("prisma:extension:optimize"),{bold:ke,dim:Ee}=le.default,me="https://optimize-ingestion.datacdn.workers.dev/",ce="https://optimize-3k7.pages.dev/",ie=`You need to login to Prisma Data Platform using the CLI to use Prisma Optimize:
|
|
2
2
|
|
|
3
|
-
${(
|
|
4
|
-
`;function
|
|
3
|
+
${Ee("$")} ${ke("prisma platform auth login --early-access")}
|
|
4
|
+
`;function Ae({enable:t=!0,ingestionUrl:e=me,dashboardUrl:n=ce,useTracing:r=!0,minSendInterval:o=50}={}){if(!t)return oe;let s=new URL(e),i=x();if(!i)if(process.stdin.isTTY){if(console.error(ie),de.default.keyInYN("Run this command now?")&&(D(),i=x()),!i)throw new Error("Please login to Prisma Data Platform in the CLI to use Prisma Optimize.")}else throw new Error(ie);return Q.dashboardReady(n).then().catch(p=>{console.error("Failed to show toast",p)}),ae.Prisma.defineExtension(p=>{let l=r?ee(s,i,o):void 0;if(r&&!te(p))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return p.$extends({query:{async $allOperations({query:R,model:T,operation:C,args:b}){let k=se.trace.getActiveSpan();if(r&&!k)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");let c=k?.spanContext().spanId,u=null,E=performance.now(),A=Date.now();c&&l?.createRequest({spanId:c,timestamp:A,model:T,operation:C,args:b});try{return await R(b)}catch(m){throw u=ne(m),await l?.forceFlush(),m}finally{let m=performance.now();if(Ce("latency raw: %d",m-E),c&&l?.setRequestError(c,u),!r){let O=async()=>{await h(s,i,[{model:T??null,operation:C,args:b,error:u,latency:m-E,ts:A,connect:!1,sql:null}])};u!==null?await O():g(O)}}}}})})}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.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -20,15 +20,17 @@
|
|
|
20
20
|
"@opentelemetry/sdk-trace-base": "1.22.0",
|
|
21
21
|
"@opentelemetry/semantic-conventions": "1.22.0",
|
|
22
22
|
"@prisma/debug": "5.12.1",
|
|
23
|
-
"@prisma/instrumentation": "5.
|
|
24
|
-
"node-notifier": "10.0.1",
|
|
23
|
+
"@prisma/instrumentation": "5.13.0",
|
|
25
24
|
"kleur": "4.1.5",
|
|
25
|
+
"node-notifier": "10.0.1",
|
|
26
|
+
"readline-sync": "1.4.10",
|
|
26
27
|
"xdg-app-paths": "8.3.0"
|
|
27
28
|
},
|
|
28
29
|
"devDependencies": {
|
|
30
|
+
"@types/node-notifier": "8.0.5",
|
|
31
|
+
"@types/readline-sync": "1.4.8",
|
|
29
32
|
"common": "workspace:*",
|
|
30
33
|
"tsup": "8.0.2",
|
|
31
|
-
"@types/node-notifier": "8.0.5",
|
|
32
34
|
"vitest": "1.4.0"
|
|
33
35
|
},
|
|
34
36
|
"peerDependencies": {
|