metergraph 0.3.2 → 0.5.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.
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Repository-aware ingest protocol v2: app-token -> session-token exchange.
3
+ *
4
+ * The app token is sent only on POST /v1/ingest/sessions. The resulting
5
+ * session token is cached in memory and reused until it's within
6
+ * REFRESH_MARGIN_MS of expiry, at which point the next getToken() call
7
+ * transparently re-exchanges it. Exchanges happen lazily, off the caller's
8
+ * request path (Transport.deliver already runs asynchronously), so a slow
9
+ * round trip here adds no latency to the customer's LLM call. Every failure
10
+ * mode is fail-open: getToken() resolves to undefined and callers drop that
11
+ * batch rather than ever sending the app token to /v1/ingest.
12
+ */
13
+ import { FailureLogger } from "./failure-log.js";
14
+ export const DEFAULT_TIMEOUT_MS = 3_000;
15
+ export const DEFAULT_TTL_MS = 300_000;
16
+ export const REFRESH_MARGIN_MS = 30_000;
17
+ export const MAX_BACKOFF_MS = 60_000;
18
+ function parseExpiresAt(value) {
19
+ if (typeof value !== "string")
20
+ return undefined;
21
+ const parsed = Date.parse(value);
22
+ return Number.isNaN(parsed) ? undefined : parsed;
23
+ }
24
+ export class SessionManager {
25
+ appToken;
26
+ repository;
27
+ sdkVersion;
28
+ timeoutMs;
29
+ url;
30
+ failureLog = new FailureLogger();
31
+ token;
32
+ expiresAt = 0;
33
+ stopped = false;
34
+ retryAt = 0;
35
+ backoffMs = 1_000;
36
+ constructor(appToken, baseUrl, repository, sdkVersion, timeoutMs = DEFAULT_TIMEOUT_MS) {
37
+ this.appToken = appToken;
38
+ this.repository = repository;
39
+ this.sdkVersion = sdkVersion;
40
+ this.timeoutMs = timeoutMs;
41
+ this.url = `${baseUrl.replace(/\/$/, "")}/v1/ingest/sessions`;
42
+ }
43
+ async getToken() {
44
+ if (this.stopped)
45
+ return undefined;
46
+ if (this.token !== undefined && Date.now() < this.expiresAt - REFRESH_MARGIN_MS) {
47
+ return this.token;
48
+ }
49
+ if (Date.now() < this.retryAt)
50
+ return undefined;
51
+ await this.exchange();
52
+ return this.stopped ? undefined : this.token;
53
+ }
54
+ invalidate() {
55
+ this.token = undefined;
56
+ this.expiresAt = 0;
57
+ this.retryAt = 0;
58
+ this.backoffMs = 1_000;
59
+ }
60
+ stop() {
61
+ this.stopped = true;
62
+ this.token = undefined;
63
+ this.expiresAt = 0;
64
+ }
65
+ async exchange() {
66
+ try {
67
+ const response = await fetch(this.url, {
68
+ method: "POST",
69
+ headers: {
70
+ Authorization: `Bearer ${this.appToken}`,
71
+ "Content-Type": "application/json",
72
+ },
73
+ body: JSON.stringify({
74
+ protocol_version: 2,
75
+ repository: this.repository,
76
+ sdk_version: this.sdkVersion,
77
+ }),
78
+ signal: AbortSignal.timeout(this.timeoutMs),
79
+ });
80
+ if (!response.ok) {
81
+ this.failureLog.report("session_exchange_error", `session exchange to ${this.url} failed with HTTP ${response.status}`);
82
+ this.markFailed();
83
+ return;
84
+ }
85
+ const doc = (await response.json());
86
+ const token = doc?.session_token;
87
+ if (typeof token !== "string" || !token) {
88
+ this.failureLog.report("session_exchange_error", `session exchange to ${this.url} returned no session_token`);
89
+ this.markFailed();
90
+ return;
91
+ }
92
+ const expiresAt = parseExpiresAt(doc?.expires_at) ?? Date.now() + DEFAULT_TTL_MS;
93
+ if (!this.stopped) {
94
+ this.token = token;
95
+ this.expiresAt = expiresAt;
96
+ this.retryAt = 0;
97
+ this.backoffMs = 1_000;
98
+ }
99
+ }
100
+ catch (error) {
101
+ this.failureLog.report("session_exchange_error", `session exchange to ${this.url} failed: ${error instanceof Error ? error.message : String(error)}`);
102
+ this.markFailed();
103
+ }
104
+ }
105
+ markFailed() {
106
+ this.retryAt = Date.now() + this.backoffMs;
107
+ this.backoffMs = Math.min(this.backoffMs * 2, MAX_BACKOFF_MS);
108
+ }
109
+ }
@@ -1,3 +1,4 @@
1
+ import type { SessionManager } from "./session.js";
1
2
  export type TransportMode = "auto" | "background" | "buffered";
2
3
  export type WaitUntil = (promise: Promise<unknown>) => void;
3
4
  export declare const MAX_BATCH_BYTES: number;
@@ -6,6 +7,7 @@ export interface TransportOptions {
6
7
  batchSize?: number;
7
8
  flushMs?: number;
8
9
  mode?: TransportMode;
10
+ session?: SessionManager;
9
11
  }
10
12
  export declare class Transport {
11
13
  private readonly token;
@@ -24,6 +26,7 @@ export declare class Transport {
24
26
  private retryAt;
25
27
  private backoffMs;
26
28
  private readonly failureLog;
29
+ private readonly session?;
27
30
  constructor(token: string, baseUrl: string, options?: TransportOptions);
28
31
  bindWaitUntil(value: {
29
32
  waitUntil(promise: Promise<unknown>): void;
package/dist/transport.js CHANGED
@@ -30,9 +30,11 @@ export class Transport {
30
30
  retryAt = 0;
31
31
  backoffMs = 1_000;
32
32
  failureLog = new FailureLogger();
33
+ session;
33
34
  constructor(token, baseUrl, options = {}) {
34
35
  this.token = token;
35
36
  this.baseUrl = baseUrl;
37
+ this.session = options.session;
36
38
  this.queueSize = Math.max(1, options.queueSize ?? 2_000);
37
39
  this.batchSize = Math.max(1, Math.min(1_000, options.batchSize ?? 100));
38
40
  this.mode = options.mode === "auto" || !options.mode ? detectedMode() : options.mode;
@@ -99,6 +101,11 @@ export class Transport {
99
101
  this.dropped += rows.length;
100
102
  return;
101
103
  }
104
+ const token = this.session ? await this.session.getToken() : this.token;
105
+ if (token === undefined) {
106
+ this.dropped += rows.length;
107
+ return;
108
+ }
102
109
  const encoded = new TextEncoder().encode(JSON.stringify({
103
110
  schema_version: 1,
104
111
  rows,
@@ -121,7 +128,7 @@ export class Transport {
121
128
  const response = await fetch(`${this.baseUrl.replace(/\/$/, "")}/v1/ingest`, {
122
129
  method: "POST",
123
130
  headers: {
124
- Authorization: `Bearer ${this.token}`,
131
+ Authorization: `Bearer ${token}`,
125
132
  "Content-Type": "application/json",
126
133
  ...(compressed && body !== raw ? { "Content-Encoding": "gzip" } : {}),
127
134
  },
@@ -129,6 +136,11 @@ export class Transport {
129
136
  keepalive: this.mode === "buffered" && body.byteLength <= 64 * 1024,
130
137
  });
131
138
  if (response.status === 401 || response.status === 403) {
139
+ if (this.session) {
140
+ this.session.invalidate();
141
+ this.dropped += rows.length;
142
+ return;
143
+ }
132
144
  this.fatal = true;
133
145
  console.warn("Metergraph authentication failed; capture disabled for this process");
134
146
  return;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.3.2";
1
+ export declare const SDK_VERSION = "0.5.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.3.2";
1
+ export const SDK_VERSION = "0.5.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metergraph",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "description": "Fire-and-forget LLM spend capture for Metergraph",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",