@prisma/extension-optimize 0.7.0 → 0.8.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 +21 -19
- package/dist/index.d.ts +4 -3
- package/dist/index.js +3 -3
- package/package.json +12 -11
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
# Optimize Prisma Client extension
|
|
1
|
+
# Prisma 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=optimize-readme)
|
|
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), which enables the use of Prisma Optimize.
|
|
4
4
|
|
|
5
|
-
Optimize enables developers to profile and get performance-related recommendations while developing applications with Prisma.
|
|
5
|
+
Prisma Optimize enables developers to profile and get performance-related recommendations while developing applications with Prisma ORM.
|
|
6
6
|
|
|
7
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
|
|
|
@@ -11,9 +11,9 @@ It is part of the [Prisma](https://www.prisma.io?utm_source=github&utm_medium=op
|
|
|
11
11
|
|
|
12
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
|
-
## Getting started with Optimize
|
|
14
|
+
## Getting started with Prisma Optimize
|
|
15
15
|
|
|
16
|
-
Enabling Optimize in your local development workflow is really simple.
|
|
16
|
+
Enabling Prisma Optimize in your local development workflow is really simple.
|
|
17
17
|
|
|
18
18
|
### 1. Install the extension
|
|
19
19
|
|
|
@@ -21,9 +21,11 @@ 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 Prisma project from scratch? Follow https://www.prisma.io/docs/getting-started
|
|
24
|
+
> Starting a Prisma ORM project from scratch? Follow https://www.prisma.io/docs/getting-started
|
|
25
25
|
|
|
26
|
-
### 2. Enable the `tracing` preview feature in your schema
|
|
26
|
+
### 2. Enable the `tracing` preview feature in your Prisma schema
|
|
27
|
+
|
|
28
|
+
Prisma Optimize uses [Prisma ORM's OpenTelemetry tracing functionality](https://www.prisma.io/docs/orm/prisma-client/observability-and-logging/opentelemetry-tracing). Enabled it in your Prisma schema:
|
|
27
29
|
|
|
28
30
|
```diff
|
|
29
31
|
generator client {
|
|
@@ -38,7 +40,7 @@ After enabling the `tracing` preview feature, you need to re-generate your Prism
|
|
|
38
40
|
npx prisma generate
|
|
39
41
|
```
|
|
40
42
|
|
|
41
|
-
### 3. Extend your Prisma Client with Optimize support
|
|
43
|
+
### 3. Extend your Prisma Client with Prisma Optimize support
|
|
42
44
|
|
|
43
45
|
```typescript
|
|
44
46
|
import { PrismaClient } from "@prisma/client";
|
|
@@ -47,21 +49,21 @@ import { withOptimize } from "@prisma/extension-optimize";
|
|
|
47
49
|
const prisma = new PrismaClient().$extends(withOptimize());
|
|
48
50
|
```
|
|
49
51
|
|
|
50
|
-
The extension will orchestrate the user experience around Optimize.
|
|
52
|
+
The extension will orchestrate the user experience around Prisma Optimize. When running your app, you will:
|
|
51
53
|
|
|
52
54
|
- Be required to log into the Prisma Data Platform through your GitHub account
|
|
53
55
|
- And be instructed to visit the URL of your Optimize dashboard:
|
|
54
56
|
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
│
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
[...]
|
|
64
|
-
```
|
|
57
|
+
```terminal
|
|
58
|
+
$ tsx index.ts
|
|
59
|
+
|
|
60
|
+
┌─────────────────────────────────┐
|
|
61
|
+
│ See your Optimize dashboard at: │
|
|
62
|
+
│ https://optimize.prisma.io/ │
|
|
63
|
+
└─────────────────────────────────┘
|
|
64
|
+
|
|
65
|
+
[...]
|
|
66
|
+
```
|
|
65
67
|
|
|
66
68
|
## Got feedback?
|
|
67
69
|
|
package/dist/index.d.ts
CHANGED
|
@@ -17,8 +17,9 @@ type OptimizeOptions = {
|
|
|
17
17
|
*/
|
|
18
18
|
dashboardUrl?: string;
|
|
19
19
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
20
|
+
* In the past, this used to configure whether to use tracing or not.
|
|
21
|
+
* This is now a no-op and will be completely removed in a future version.
|
|
22
|
+
* @deprecated
|
|
22
23
|
*/
|
|
23
24
|
useTracing?: boolean;
|
|
24
25
|
/**
|
|
@@ -32,6 +33,6 @@ type OptimizeOptions = {
|
|
|
32
33
|
*/
|
|
33
34
|
showToast?: boolean;
|
|
34
35
|
};
|
|
35
|
-
declare function withOptimize({ enable, ingestionUrl, dashboardUrl,
|
|
36
|
+
declare function withOptimize({ enable, ingestionUrl, dashboardUrl, minSendInterval, showToast, }?: OptimizeOptions): (client: any) => _prisma_client_extension.PrismaClientExtends<_prisma_client_runtime_library.InternalArgs<{}, {}, {}, {}> & _prisma_client_runtime_library.DefaultArgs>;
|
|
36
37
|
|
|
37
38
|
export { type OptimizeOptions, PROD_DASHBOARD_URL, PROD_INGESTION_URL, withOptimize };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var le=Object.create;var c=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var ue=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty;var he=(t,e)=>{for(var n in e)c(t,n,{get:e[n],enumerable:!0})},C=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ce(e))!fe.call(t,o)&&o!==n&&c(t,o,{get:()=>e[o],enumerable:!(r=de(e,o))||r.enumerable});return t};var s=(t,e,n)=>(n=t!=null?le(ue(t)):{},C(e||!t||!t.__esModule?c(n,"default",{value:t,enumerable:!0}):n,t)),ge=t=>C(c({},"__esModule",{value:!0}),t);var ve={};he(ve,{PROD_DASHBOARD_URL:()=>se,PROD_INGESTION_URL:()=>ie,withOptimize:()=>Te});module.exports=ge(ve);var te=require("@opentelemetry/api"),ne=require("@prisma/client/extension"),re=s(require("kleur")),oe=s(require("readline-sync"));var T=s(require("fs")),v=s(require("path")),k=s(require("@prisma/debug")),q=s(require("xdg-app-paths")),Se=(0,k.default)("prisma:extension:optimize"),ye=new q.default("prisma-platform-cli").config(),we=v.default.join(ye,"auth.json");function Re(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 S(){try{let t=T.default.readFileSync(we,"utf-8");return Re(JSON.parse(t)).token}catch(t){return Se(t),null}}var E=require("child_process");function z(){let t=(0,E.spawnSync)("npx",["--yes","prisma@optimize","platform","auth","login","--early-access","--optimize"],{stdio:"inherit",shell:!0});if(t.error)throw t.error}var l=s(require("fs")),O=s(require("path")),A=require("stream"),L=require("stream/promises"),M=s(require("kleur")),U=require("node-notifier"),F=s(require("xdg-app-paths")),Ie="https://avatars.githubusercontent.com/u/17219288?s=96",{bold:be,underline:xe}=M.default;async function _(t){let e=new F.default("prisma-optimize").config();l.default.mkdirSync(e,{recursive:!0});let n=O.default.resolve(e,"avatar.png");if(!l.default.existsSync(n)){let m=await fetch(Ie);if(m.ok&&m.body!=null){let h=l.default.createWriteStream(n,{flags:"wx"});await(0,L.finished)(A.Readable.fromWeb(m.body).pipe(h))}}let r="See your Optimize dashboard at:",o=r.length,i=`${xe(be(t))}`,a=t.length,p=Math.max(o,a)+2;console.log("\u250C"+"\u2500".repeat(p)+"\u2510"),console.log("\u2502 "+r+" ".repeat(p-o-2)+" \u2502"),console.log("\u2502 "+i+" ".repeat(p-a-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(p)+"\u2518"),(0,U.notify)({timeout:10,open:t,subtitle:"Your dashboard is ready! \u{1F680} ",message:"Click to open",title:"Prisma Optimize",icon:l.default.existsSync(n)?n:void 0,contentImage:l.default.existsSync(n)?n:void 0})}var J=require("@opentelemetry/api"),B=require("@opentelemetry/context-async-hooks"),Q=require("@opentelemetry/instrumentation"),H=require("@opentelemetry/resources"),V=require("@opentelemetry/sdk-trace-base"),f=require("@opentelemetry/semantic-conventions"),W=require("@prisma/instrumentation");var j=s(require("@prisma/debug"));var y;async function N(t,e,n){let r=new URL("/ingest",t),o=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});y&&o.set("prisma-optimize-jwt",y);let i=await fetch(r,{method:"POST",headers:o,body:JSON.stringify(n)});if(!i.ok){console.error(`[optimize] HTTP ${i.status} ${i.statusText}: ${await i.text()}`),i.status===401&&(console.error("[optimize] Try logging out, run `npx prisma@optimize platform auth logout --early-access --optimize`"),console.error("[optimize] And log in again, run `npx prisma@optimize platform auth login --early-access --optimize`"));return}let a=i.headers.get("prisma-optimize-jwt");a&&(y=a)}function w(t,...e){setTimeout(()=>{t(...e)},0)}function d(t){return t[0]*1e3+t[1]/1e6}var I=(0,j.default)("prisma:extension:optimize"),R="0000000000000000",D=(o=>(o.ClientOperation="prisma:client:operation",o.ClientConnect="prisma:client:connect",o.Engine="prisma:engine",o.EngineQuery="prisma:engine:db_query",o))(D||{}),b=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((n,r)=>{let o=d(n.startTime),i=d(r.startTime);return o-i}).reduce((n,r)=>{let o=r.attributes["db.statement"];return typeof o=="string"?`${n}${o}
|
|
2
|
+
`:(I("sql attribute is not a string: %o",o),n)},"")}toIngestRequestItem(){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}}},u=class{#e=new Map;#o=Promise.resolve();#t=new Map;#n=new Map;#a;#p;#m;#r=new Set;#l=Promise.resolve();#i=!1;constructor(e,n,r){this.#a=e,this.#p=n,this.#m=r}createRequest(e){let n=new b(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!==R;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){if(!$(e))return;let r=e.spanContext().spanId;if(!e.parentSpanId){this.#t.set(r,R);return}if(this.#t.set(r,e.parentSpanId),e.parentSpanId===R)return;let o=this.#n.get(e.parentSpanId);o?o.add(r):this.#n.set(e.parentSpanId,new Set([r]))}onEnd(e){$(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.#s(n);break}if(r){switch(e.name){case"prisma:client:connect":{r.connect=d(e.duration);break}case"prisma:engine":{r.completionFlags.engineSpanClosed=!0;break}case"prisma:engine:db_query":{r.statementSpans.push(e);break}case"prisma:client:operation":{r.duration=d(e.duration),r.completionFlags.clientSpanClosed=!0,I("latency otel: %d",r.duration);break}}r.isCompleted()&&this.#h(r)}}#f(e){this.#o=Promise.all([this.#o,new Promise(w).then(()=>this.#d(e))])}#s(e){this.#t.delete(e);let n=this.#n.get(e);if(this.#n.delete(e),n)for(let r of n)this.#s(r)}#h(e){w(()=>{this.#e.delete(e.spanId),this.#s(e.spanId),this.#r.add(e),this.#g()})}async#g(){await this.#l,!this.#i&&(this.#i=!0,setTimeout(()=>{this.#l=this.#c().finally(()=>{this.#i=!1})},this.#m))}async#c(){if(this.#r.size===0)return;let e=[...this.#r].map(n=>n.toIngestRequestItem());this.#r.clear(),I("sending batch of %d requests",e.length),await N(this.#a,this.#p,e)}};function $(t){return Object.values(D).includes(t.name)}function Y(t,e,n){let r=new B.AsyncHooksContextManager().enable();J.context.setGlobalContextManager(r);let o=new V.BasicTracerProvider({resource:new H.Resource({[f.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[f.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})}),i=new u(t,e,n);return o.addSpanProcessor(i),(0,Q.registerInstrumentations)({tracerProvider:o,instrumentations:[new W.PrismaInstrumentation]}),o.register(),i}function G(t){return t._previewFeatures?.includes("tracing")}function X(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 Z=require("@prisma/client/extension"),K=Z.Prisma.defineExtension(t=>t.$extends({}));var{bold:Pe,dim:Ce}=re.default,ie="https://optimize-ingestion.datacdn.workers.dev/",se="https://optimize.prisma.io",ee=`You need to login to Prisma Data Platform using the CLI to use Prisma Optimize:
|
|
2
3
|
|
|
3
|
-
${
|
|
4
|
-
`;function ze({enable:t=!0,ingestionUrl:e=de,dashboardUrl:n=ce,useTracing:r=!0,minSendInterval:o=50,showToast:i=!0}={}){if(!t)return oe;let s=new URL(e),p=I();if(!p)if(process.stdin.isTTY){if(console.error(ie),me.default.keyInYN("Run this command now?")&&(D(),p=I()),!p)throw new Error("Please login to Prisma Data Platform in the CLI to use Prisma Optimize.")}else throw new Error(ie);return i&&Q(n).then().catch(l=>{console.error("Failed to show toast",l)}),ae.Prisma.defineExtension(l=>{let d=r?ee(s,p,o):void 0;if(r&&!te(l))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return l.$extends({query:{async $allOperations({query:ue,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 u=k?.spanContext().spanId,f=null,E=performance.now(),z=Date.now();u&&d?.createRequest({spanId:u,timestamp:z,model:T,operation:C,args:b});try{return await ue(b)}catch(c){throw f=ne(c),await d?.forceFlush(),c}finally{let c=performance.now();if(Ce("latency raw: %d",c-E),u&&d?.setRequestError(u,f),!r){let A=async()=>{await g(s,p,[{model:T??null,operation:C,args:b,error:f,latency:c-E,ts:z,connect:!1,sql:null}])};f!==null?await A():S(A)}}}}})})}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
|
|
4
|
+
${Ce("$")} ${Pe("npx prisma@optimize platform auth login --early-access --optimize")}`;function Te({enable:t=!0,ingestionUrl:e=ie,dashboardUrl:n=se,minSendInterval:r=50,showToast:o=!0}={}){if(!t)return K;let i=new URL(e),a=S();if(!a)if(process.stdin.isTTY){if(console.error(ee),oe.default.keyInYN("Run this command now?")&&(z(),a=S()),!a)throw new Error("Please login to Prisma Data Platform in the CLI to use Prisma Optimize.")}else throw new Error(ee);return o&&_(n).then().catch(p=>{console.error("Failed to show toast",p)}),ne.Prisma.defineExtension(p=>{let m=Y(i,a,r);if(!G(p))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');return p.$extends({query:{async $allOperations({query:h,model:ae,operation:pe,args:x}){let g=te.trace.getActiveSpan()?.spanContext().spanId;if(!g)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");m.createRequest({spanId:g,timestamp:Date.now(),model:ae,operation:pe,args:x});try{return await h(x)}catch(P){let me=X(P);throw m.setRequestError(g,me),P}}}})})}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
|
package/package.json
CHANGED
|
@@ -1,15 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/extension-optimize",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
|
+
"sideEffects": false,
|
|
4
5
|
"description": "",
|
|
5
6
|
"main": "./dist/index.js",
|
|
6
7
|
"types": "./dist/index.d.ts",
|
|
7
|
-
"scripts": {
|
|
8
|
-
"typecheck": "tsc --noEmit",
|
|
9
|
-
"build": "tsup src/index.ts --minify --dts --format cjs --out-dir dist",
|
|
10
|
-
"lint": "eslint --fix .",
|
|
11
|
-
"test": "vitest --run"
|
|
12
|
-
},
|
|
13
8
|
"keywords": [],
|
|
14
9
|
"dependencies": {
|
|
15
10
|
"@opentelemetry/api": "1.8.0",
|
|
@@ -29,14 +24,20 @@
|
|
|
29
24
|
"devDependencies": {
|
|
30
25
|
"@types/node-notifier": "8.0.5",
|
|
31
26
|
"@types/readline-sync": "1.4.8",
|
|
32
|
-
"common": "workspace:*",
|
|
33
27
|
"tsup": "8.0.2",
|
|
34
|
-
"vitest": "1.4.0"
|
|
28
|
+
"vitest": "1.4.0",
|
|
29
|
+
"common": "0.0.0"
|
|
35
30
|
},
|
|
36
31
|
"peerDependencies": {
|
|
37
32
|
"@prisma/client": "5.x"
|
|
38
33
|
},
|
|
39
34
|
"files": [
|
|
40
35
|
"dist"
|
|
41
|
-
]
|
|
42
|
-
|
|
36
|
+
],
|
|
37
|
+
"scripts": {
|
|
38
|
+
"typecheck": "tsc --noEmit",
|
|
39
|
+
"build": "tsup src/index.ts --minify --dts --format cjs --out-dir dist",
|
|
40
|
+
"lint": "eslint --fix .",
|
|
41
|
+
"test": "vitest --run"
|
|
42
|
+
}
|
|
43
|
+
}
|