@prisma/extension-optimize 0.0.0-dev.202408261016 → 0.0.0-dev.202408261039
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 +27 -50
- package/dist/index.d.ts +9 -4
- package/dist/index.js +4 -2
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -13,26 +13,19 @@ Prisma is leading Data DX, a philosophy that promotes simplicity in data-driven
|
|
|
13
13
|
|
|
14
14
|
## Getting started with Prisma Optimize
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
Enabling Prisma Optimize in your local development workflow is really simple.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
### 1. Install the extension
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
### Using Optimize
|
|
25
|
-
|
|
26
|
-
#### 1. Launch Optimize
|
|
27
|
-
|
|
28
|
-
1. Log in to your [Prisma Data Platform](https://console.prisma.io/login?utm_source=github&utm_medium=optimize-readme) account.
|
|
29
|
-
2. Access and launch the Optimize dashboard by following the instructions here.
|
|
20
|
+
```
|
|
21
|
+
npm install @prisma/extension-optimize --save-dev
|
|
22
|
+
```
|
|
30
23
|
|
|
31
|
-
|
|
24
|
+
> Starting a Prisma ORM project from scratch? Follow https://www.prisma.io/docs/getting-started
|
|
32
25
|
|
|
33
|
-
|
|
26
|
+
### 2. Enable the `tracing` preview feature in your Prisma schema
|
|
34
27
|
|
|
35
|
-
Prisma Optimize uses [Prisma ORM's OpenTelemetry tracing functionality](https://www.prisma.io/docs/orm/prisma-client/observability-and-logging/opentelemetry-tracing).
|
|
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:
|
|
36
29
|
|
|
37
30
|
```diff
|
|
38
31
|
generator client {
|
|
@@ -41,53 +34,37 @@ Prisma Optimize uses [Prisma ORM's OpenTelemetry tracing functionality](https://
|
|
|
41
34
|
}
|
|
42
35
|
```
|
|
43
36
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
```shell
|
|
47
|
-
npx prisma generate
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
##### 2.2. Install the Optimize Prisma Client extension
|
|
51
|
-
|
|
52
|
-
Install the latest versions of Prisma Client and the Optimize extension:
|
|
37
|
+
After enabling the `tracing` preview feature, you need to re-generate your Prisma Client:
|
|
53
38
|
|
|
54
|
-
```shell
|
|
55
|
-
npm install @prisma/client@latest @prisma/extension-optimize
|
|
56
39
|
```
|
|
57
|
-
|
|
58
|
-
##### 2.3. Create an API Key via Optimize's UI and add it to your .env file
|
|
59
|
-
|
|
60
|
-
Generate an Optimize API key by following the instructions [here](https://pris.ly/optimize/r/api-token-generation) and add it to your .env file:
|
|
61
|
-
|
|
62
|
-
```env
|
|
63
|
-
OPTIMIZE_API_KEY="YOUR_OPTIMIZE_API_KEY"
|
|
40
|
+
npx prisma generate
|
|
64
41
|
```
|
|
65
42
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
Extend your existing Prisma Client instance with the Optimize extension:
|
|
43
|
+
### 3. Extend your Prisma Client with Prisma Optimize support
|
|
69
44
|
|
|
70
45
|
```typescript
|
|
71
46
|
import { PrismaClient } from "@prisma/client";
|
|
72
47
|
import { withOptimize } from "@prisma/extension-optimize";
|
|
73
48
|
|
|
74
|
-
const prisma = new PrismaClient().$extends(withOptimize(
|
|
49
|
+
const prisma = new PrismaClient().$extends(withOptimize());
|
|
75
50
|
```
|
|
76
51
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
Follow these steps to start generating query insights with Prisma Optimize:
|
|
80
|
-
|
|
81
|
-
1. In the Optimize dashboard, click the Start recording button, then run your app.
|
|
82
|
-
|
|
83
|
-
2. After your app runs and insights are generated for the desired queries, click the Stop recording button.
|
|
84
|
-
|
|
85
|
-
3. Explore individual query details by clicking on them, and check the Recommendations tab for any suggested improvements to enhance query performance.
|
|
52
|
+
The extension will orchestrate the user experience around Prisma Optimize. When running your app, you will:
|
|
86
53
|
|
|
87
|
-
|
|
54
|
+
- Be required to log into the Prisma Data Platform through your GitHub account
|
|
55
|
+
- And be instructed to visit the URL of your Optimize dashboard:
|
|
88
56
|
|
|
89
|
-
|
|
57
|
+
```terminal
|
|
58
|
+
$ tsx index.ts
|
|
59
|
+
|
|
60
|
+
┌─────────────────────────────────┐
|
|
61
|
+
│ See your Optimize dashboard at: │
|
|
62
|
+
│ https://optimize.prisma.io/ │
|
|
63
|
+
└─────────────────────────────────┘
|
|
64
|
+
|
|
65
|
+
[...]
|
|
66
|
+
```
|
|
90
67
|
|
|
91
|
-
|
|
68
|
+
## Got feedback?
|
|
92
69
|
|
|
93
|
-
|
|
70
|
+
Please [submit an issue](https://github.com/prisma/optimize-feedback/issues/new/choose) or [join a discussion](https://github.com/prisma/optimize-feedback/discussions) in our [feedback repository](https://github.com/prisma/optimize-feedback/)
|
package/dist/index.d.ts
CHANGED
|
@@ -17,10 +17,15 @@ type OptimizeOptions = {
|
|
|
17
17
|
*/
|
|
18
18
|
dashboardUrl?: string;
|
|
19
19
|
/**
|
|
20
|
-
*
|
|
21
|
-
* create one.
|
|
20
|
+
* The token to use to authenticate Prisma Optimize
|
|
22
21
|
*/
|
|
23
|
-
token
|
|
22
|
+
token?: string;
|
|
23
|
+
/**
|
|
24
|
+
* In the past, this used to configure whether to use tracing or not.
|
|
25
|
+
* This is now a no-op and will be completely removed in a future version.
|
|
26
|
+
* @deprecated
|
|
27
|
+
*/
|
|
28
|
+
useTracing?: boolean;
|
|
24
29
|
/**
|
|
25
30
|
* The minimum interval in milliseconds between sending batched requests to the ingestion service.
|
|
26
31
|
* This is only currently used when tracing is enabled. When tracing is disabled, the requests
|
|
@@ -32,6 +37,6 @@ type OptimizeOptions = {
|
|
|
32
37
|
*/
|
|
33
38
|
showToast?: boolean;
|
|
34
39
|
};
|
|
35
|
-
declare function withOptimize({ enable, ingestionUrl, dashboardUrl, minSendInterval, showToast, token, }
|
|
40
|
+
declare function withOptimize({ enable, ingestionUrl, dashboardUrl, minSendInterval, showToast, token: givenToken, }?: OptimizeOptions): (client: any) => _prisma_client_extension.PrismaClientExtends<_prisma_client_runtime_library.InternalArgs<{}, {}, {}, {}> & _prisma_client_runtime_library.DefaultArgs>;
|
|
36
41
|
|
|
37
42
|
export { type OptimizeOptions, PROD_DASHBOARD_URL, PROD_INGESTION_URL, withOptimize };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`:(
|
|
1
|
+
"use strict";var ge=Object.create;var f=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty;var be=(t,e)=>{for(var n in e)f(t,n,{get:e[n],enumerable:!0})},v=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ye(e))!Ce.call(t,o)&&o!==n&&f(t,o,{get:()=>e[o],enumerable:!(r=Se(e,o))||r.enumerable});return t};var a=(t,e,n)=>(n=t!=null?ge(we(t)):{},v(e||!t||!t.__esModule?f(n,"default",{value:t,enumerable:!0}):n,t)),Re=t=>v(f({},"__esModule",{value:!0}),t);var Le={};be(Le,{PROD_DASHBOARD_URL:()=>le,PROD_INGESTION_URL:()=>ce,withOptimize:()=>Fe});module.exports=Re(Le);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 xe(t,e){let n;return async function(r,o,p){let c=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(c,{method:o,headers:s,body:JSON.stringify(p)});if(!i.ok){let l=await i.text().catch(()=>"<unreadable>");throw console.error(`[optimize] HTTP ${i.status} ${i.statusText}: ${l}`),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}: ${l}`)}let m=i.headers.get("prisma-optimize-jwt");return m&&(n=m),i}}function T(t,e){let n=xe(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")),k=a(require("path")),A=require("@prisma/debug"),z=a(require("xdg-app-paths")),Ie=(0,A.Debug)("prisma:extension:optimize"),Pe=new z.default("prisma-platform-cli").config(),ve=k.default.join(Pe,"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(ve,"utf-8");return Te(JSON.parse(t)).token}catch(t){return Ie(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 u=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")),qe="https://avatars.githubusercontent.com/u/17219288?s=96",{bold:Ee,underline:ke}=$.default;async function N(t){let e=new j.default("prisma-optimize").config();u.default.mkdirSync(e,{recursive:!0});let n=L.default.resolve(e,"avatar.png");if(!u.default.existsSync(n)){let i=await fetch(qe);if(i.ok&&i.body!=null){let m=u.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,p=`${ke(Ee(t))}`,c=t.length,s=Math.max(o,c)+2;console.log("\u250C"+"\u2500".repeat(s)+"\u2510"),console.log("\u2502 "+r+" ".repeat(s-o-2)+" \u2502"),console.log("\u2502 "+p+" ".repeat(s-c-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:u.default.existsSync(n)?n:void 0,contentImage:u.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 h(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=h(n.startTime),p=h(r.startTime);return o-p}).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,hash: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=h(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=h(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:ze}=pe.default,ce="https://optimize-ingestion.datacdn.workers.dev/",le="https://optimize.prisma.io",Oe=(0,ae.default)("prisma:extension:optimize"),oe=`You need to login to Prisma Data Platform using the CLI to use Prisma Optimize:
|
|
3
|
+
|
|
4
|
+
${ze("$")} ${Ae("npx prisma@optimize platform auth login --early-access --optimize")}`;function Fe({enable:t=!0,ingestionUrl:e=ce,dashboardUrl:n=le,minSendInterval:r=50,showToast:o=!0,token:p}={}){if(!t)return re;let c=new URL(e),s=p??w();if(!s)if(process.stdin.isTTY){if(console.error(oe),me.default.keyInYN("Run this command now?")&&(F(),s=w()),!s)throw new Error("Please login to Prisma Data Platform to use Prisma Optimize: either via the CLI, or by providing `token` as an option to `withOptimize()`")}else throw new Error(oe);return o&&N(n).then().catch(i=>{console.error("Failed to show toast",i)}),se.Prisma.defineExtension(i=>{let m=T(c,s),l=Z(m,r);if(!K(i))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');let de=ee(i);return q(m,de).then(d=>{Oe("uploaded schema with hash",d),l.setSchemaHash(d)},d=>{console.error(d),console.error("Failed to upload the schema, no data will be sent to Prisma Optimize")}),i.$extends({query:{async $allOperations({query:d,model:ue,operation:he,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");l.createRequest({spanId:y,timestamp:Date.now(),model:ue,operation:he,args:I});try{return await d(I)}catch(P){let fe=te(P);throw l.setRequestError(y,fe),P}}}})})}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.
|
|
3
|
+
"version": "0.0.0-dev.202408261039",
|
|
4
4
|
"sideEffects": false,
|
|
5
5
|
"description": "",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"@opentelemetry/resources": "1.22.0",
|
|
16
16
|
"@opentelemetry/semantic-conventions": "1.22.0",
|
|
17
17
|
"@prisma/debug": "5.12.1",
|
|
18
|
-
"@prisma/instrumentation": "5.
|
|
18
|
+
"@prisma/instrumentation": "5.14.0-dev.65",
|
|
19
19
|
"kleur": "4.1.5",
|
|
20
20
|
"node-notifier": "10.0.1",
|
|
21
21
|
"readline-sync": "1.4.10",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"hono": "4.4.6",
|
|
29
29
|
"tsup": "8.0.2",
|
|
30
30
|
"vitest": "1.4.0",
|
|
31
|
-
"common": "0.0.0-dev.
|
|
31
|
+
"common": "0.0.0-dev.202408261039"
|
|
32
32
|
},
|
|
33
33
|
"peerDependencies": {
|
|
34
34
|
"@prisma/client": "5.x"
|