@prisma/extension-optimize 0.7.1 → 0.9.0-dev.1
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 -2
- package/package.json +4 -1
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,3 +1,4 @@
|
|
|
1
|
-
"use strict";var fe=Object.create;var
|
|
1
|
+
"use strict";var fe=Object.create;var f=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var Ce=(t,e)=>{for(var n in e)f(t,n,{get:e[n],enumerable:!0})},T=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Se(e))!we.call(t,o)&&o!==n&&f(t,o,{get:()=>e[o],enumerable:!(r=ge(e,o))||r.enumerable});return t};var a=(t,e,n)=>(n=t!=null?fe(ye(t)):{},T(e||!t||!t.__esModule?f(n,"default",{value:t,enumerable:!0}):n,t)),be=t=>T(f({},"__esModule",{value:!0}),t);var Fe={};Ce(Fe,{PROD_DASHBOARD_URL:()=>le,PROD_INGESTION_URL:()=>ce,withOptimize:()=>Oe});module.exports=be(Fe);var ie=require("@opentelemetry/api"),se=require("@prisma/client/extension"),ae=a(require("@prisma/debug")),pe=a(require("kleur")),me=a(require("readline-sync"));function Re(t,e){let n;return async function(r,o,c){let p=new URL(r,t),s=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});n&&s.set("prisma-optimize-jwt",n);let i=await fetch(p,{method:o,headers:s,body:JSON.stringify(c)});if(!i.ok){let h=await i.text().catch(()=>"<unreadable>");throw console.error(`[optimize] HTTP ${i.status} ${i.statusText}: ${h}`),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`")),new Error(`Optimize error ${i.status} ${i.statusText}: ${h}`)}let m=i.headers.get("prisma-optimize-jwt");return m&&(n=m),i}}function v(t,e){let n=Re(t,e);return{request:n,post:(r,o)=>n(r,"POST",o)}}async function q(t,e){return(await t.post("/schema",{schema:e})).text()}var E=a(require("fs")),A=a(require("path")),k=a(require("@prisma/debug")),z=a(require("xdg-app-paths")),xe=(0,k.default)("prisma:extension:optimize"),Ie=new z.default("prisma-platform-cli").config(),Pe=A.default.join(Ie,"auth.json");function Te(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 w(){try{let t=E.default.readFileSync(Pe,"utf-8");return Te(JSON.parse(t)).token}catch(t){return xe(t),null}}var O=require("child_process");function F(){let t=(0,O.spawnSync)("npx",["--yes","prisma@optimize","platform","auth","login","--early-access","--optimize"],{stdio:"inherit",shell:!0});if(t.error)throw t.error}var d=a(require("fs")),L=a(require("path")),M=require("stream"),_=require("stream/promises"),$=a(require("kleur")),U=require("node-notifier"),j=a(require("xdg-app-paths")),ve="https://avatars.githubusercontent.com/u/17219288?s=96",{bold:qe,underline:Ee}=$.default;async function N(t){let e=new j.default("prisma-optimize").config();d.default.mkdirSync(e,{recursive:!0});let n=L.default.resolve(e,"avatar.png");if(!d.default.existsSync(n)){let i=await fetch(ve);if(i.ok&&i.body!=null){let m=d.default.createWriteStream(n,{flags:"wx"});await(0,_.finished)(M.Readable.fromWeb(i.body).pipe(m))}}let r="See your Optimize dashboard at:",o=r.length,c=`${Ee(qe(t))}`,p=t.length,s=Math.max(o,p)+2;console.log("\u250C"+"\u2500".repeat(s)+"\u2510"),console.log("\u2502 "+r+" ".repeat(s-o-2)+" \u2502"),console.log("\u2502 "+c+" ".repeat(s-p-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(s)+"\u2518"),(0,U.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=require("@opentelemetry/api"),V=require("@opentelemetry/context-async-hooks"),W=require("@opentelemetry/instrumentation"),Y=require("@opentelemetry/resources"),G=require("@opentelemetry/sdk-trace-base"),S=require("@opentelemetry/semantic-conventions"),X=require("@prisma/instrumentation");var J=a(require("@prisma/debug"));async function D(t,e){await t.post("/ingest",e)}function C(t,...e){setTimeout(()=>{t(...e)},0)}function u(t){return t[0]*1e3+t[1]/1e6}var R=(0,J.default)("prisma:extension:optimize"),b="0000000000000000",B=(o=>(o.ClientOperation="prisma:client:operation",o.ClientConnect="prisma:client:connect",o.Engine="prisma:engine",o.EngineQuery="prisma:engine:db_query",o))(B||{}),x=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=u(n.startTime),c=u(r.startTime);return o-c}).reduce((n,r)=>{let o=r.attributes["db.statement"];return typeof o=="string"?`${n}${o}
|
|
2
|
+
`:(R("sql attribute is not a string: %o",o),n)},"")}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,schema:e}}},g=class{#e=new Map;#o=Promise.resolve();#t=new Map;#n=new Map;#a;#p;#r=new Set;#m=Promise.resolve();#i=!1;#c;setSchemaHash=()=>{};constructor(e,n){this.#a=e,this.#p=n,this.#c=new Promise(r=>{this.setSchemaHash=r})}createRequest(e){let n=new x(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!==b;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(!H(e))return;let r=e.spanContext().spanId;if(!e.parentSpanId){this.#t.set(r,b);return}if(this.#t.set(r,e.parentSpanId),e.parentSpanId===b)return;let o=this.#n.get(e.parentSpanId);o?o.add(r):this.#n.set(e.parentSpanId,new Set([r]))}onEnd(e){H(e)&&this.#l(e)}async forceFlush(){await this.#o,await this.#d()}async shutdown(){await this.forceFlush()}#l(e){let n=e.spanContext().spanId,r,o=this.#u(n);switch(o.type){case"Ok":r=o.request;break;case"UndeliveredSpanInTree":this.#h(e);break;case"NotInRequestTree":this.#s(n);break}if(r){switch(e.name){case"prisma:client:connect":{r.connect=u(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=u(e.duration),r.completionFlags.clientSpanClosed=!0,R("latency otel: %d",r.duration);break}}r.isCompleted()&&this.#f(r)}}#h(e){this.#o=Promise.all([this.#o,new Promise(C).then(()=>this.#l(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)}#f(e){C(()=>{this.#e.delete(e.spanId),this.#s(e.spanId),this.#r.add(e),this.#g()})}async#g(){await this.#m,!this.#i&&(this.#i=!0,setTimeout(()=>{this.#m=this.#d().finally(()=>{this.#i=!1})},this.#p))}async#d(){if(this.#r.size===0)return;let e=await this.#c,n=[...this.#r].map(r=>r.toIngestRequestItem(e));this.#r.clear(),R("sending batch of %d requests",n.length);try{await D(this.#a,n)}catch(r){console.error(r.message??r)}}};function H(t){return Object.values(B).includes(t.name)}function Z(t,e){let n=new V.AsyncHooksContextManager().enable();Q.context.setGlobalContextManager(n);let r=new G.BasicTracerProvider({resource:new Y.Resource({[S.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[S.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})}),o=new g(t,e);return r.addSpanProcessor(o),(0,W.registerInstrumentations)({tracerProvider:r,instrumentations:[new X.PrismaInstrumentation]}),r.register(),o}function K(t){return t._previewFeatures?.includes("tracing")}function ee(t){return t._engineConfig.inlineSchema}function te(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 ne=require("@prisma/client/extension"),re=ne.Prisma.defineExtension(t=>t.$extends({}));var{bold:Ae,dim:ke}=pe.default,ce="https://optimize-ingestion.datacdn.workers.dev/",le="https://optimize.prisma.io",ze=(0,ae.default)("prisma:extension:optimize"),oe=`You need to login to Prisma Data Platform using the CLI to use Prisma Optimize:
|
|
2
3
|
|
|
3
|
-
${
|
|
4
|
+
${ke("$")} ${Ae("npx prisma@optimize platform auth login --early-access --optimize")}`;function Oe({enable:t=!0,ingestionUrl:e=ce,dashboardUrl:n=le,minSendInterval:r=50,showToast:o=!0}={}){if(!t)return re;let c=new URL(e),p=w();if(!p)if(process.stdin.isTTY){if(console.error(oe),me.default.keyInYN("Run this command now?")&&(F(),p=w()),!p)throw new Error("Please login to Prisma Data Platform in the CLI to use Prisma Optimize.")}else throw new Error(oe);return o&&N(n).then().catch(s=>{console.error("Failed to show toast",s)}),se.Prisma.defineExtension(s=>{let i=v(c,p),m=Z(i,r);if(!K(s))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');let h=ee(s);return q(i,h).then(l=>{ze("uploaded schema with hash",l),m.setSchemaHash(l)},l=>{console.error(l),console.error("Failed to upload the schema, no data will be sent to Prisma Optimize")}),s.$extends({query:{async $allOperations({query:l,model:de,operation:ue,args:I}){let y=ie.trace.getActiveSpan()?.spanContext().spanId;if(!y)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");m.createRequest({spanId:y,timestamp:Date.now(),model:de,operation:ue,args:I});try{return await l(I)}catch(P){let he=te(P);throw m.setRequestError(y,he),P}}}})})}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/extension-optimize",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0-dev.1",
|
|
4
|
+
"sideEffects": false,
|
|
4
5
|
"description": "",
|
|
5
6
|
"main": "./dist/index.js",
|
|
6
7
|
"types": "./dist/index.d.ts",
|
|
@@ -27,9 +28,11 @@
|
|
|
27
28
|
"xdg-app-paths": "8.3.0"
|
|
28
29
|
},
|
|
29
30
|
"devDependencies": {
|
|
31
|
+
"@hono/node-server": "1.9.1",
|
|
30
32
|
"@types/node-notifier": "8.0.5",
|
|
31
33
|
"@types/readline-sync": "1.4.8",
|
|
32
34
|
"common": "workspace:*",
|
|
35
|
+
"hono": "4.4.6",
|
|
33
36
|
"tsup": "8.0.2",
|
|
34
37
|
"vitest": "1.4.0"
|
|
35
38
|
},
|