@object-ui/data-objectstack 3.1.5 → 3.3.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.
@@ -410,6 +410,57 @@ describe('MetadataCache', () => {
410
410
  expect(fetcher).toHaveBeenCalledTimes(1);
411
411
  });
412
412
 
413
+ it('should coalesce concurrent fetches for the same key', async () => {
414
+ let resolveFetch: (v: { data: string }) => void = () => {};
415
+ const fetcher = vi.fn(
416
+ () =>
417
+ new Promise<{ data: string }>((resolve) => {
418
+ resolveFetch = resolve;
419
+ })
420
+ );
421
+
422
+ const p1 = cache.get('shared-key', fetcher);
423
+ const p2 = cache.get('shared-key', fetcher);
424
+ const p3 = cache.get('shared-key', fetcher);
425
+
426
+ // All three calls should share a single in-flight fetcher invocation
427
+ expect(fetcher).toHaveBeenCalledTimes(1);
428
+
429
+ resolveFetch({ data: 'shared' });
430
+ const [r1, r2, r3] = await Promise.all([p1, p2, p3]);
431
+
432
+ expect(r1).toEqual({ data: 'shared' });
433
+ expect(r2).toBe(r1);
434
+ expect(r3).toBe(r1);
435
+
436
+ const stats = cache.getStats();
437
+ expect(stats.coalesced).toBe(2);
438
+ expect(stats.misses).toBe(1);
439
+ });
440
+
441
+ it('should clear inflight slot after fetch rejection so retries are possible', async () => {
442
+ const fetcher = vi
443
+ .fn()
444
+ .mockRejectedValueOnce(new Error('boom'))
445
+ .mockResolvedValueOnce({ data: 'ok' });
446
+
447
+ await expect(cache.get('retry-key', fetcher)).rejects.toThrow('boom');
448
+ const result = await cache.get('retry-key', fetcher);
449
+
450
+ expect(result).toEqual({ data: 'ok' });
451
+ expect(fetcher).toHaveBeenCalledTimes(2);
452
+ });
453
+
454
+ it('should expose prime() to seed cache from bulk endpoints', async () => {
455
+ cache.prime('object:account', { name: 'account', fields: [] });
456
+
457
+ const fetcher = vi.fn(async () => ({ name: 'account', fields: [{ name: 'id' }] }));
458
+ const result = await cache.get('object:account', fetcher);
459
+
460
+ expect(fetcher).not.toHaveBeenCalled();
461
+ expect(result).toEqual({ name: 'account', fields: [] });
462
+ });
463
+
413
464
  it('should handle very large cache', async () => {
414
465
  const largeCache = new MetadataCache({ maxSize: 10000, ttl: 60000 });
415
466
 
@@ -25,6 +25,8 @@ export interface CacheStats {
25
25
  hits: number;
26
26
  misses: number;
27
27
  evictions: number;
28
+ /** Number of concurrent fetches that were coalesced onto an in-flight request. */
29
+ coalesced: number;
28
30
  hitRate: number;
29
31
  }
30
32
 
@@ -38,9 +40,9 @@ export interface CacheStats {
38
40
  * - Async-safe operations
39
41
  * - Performance statistics tracking
40
42
  *
41
- * Note: Concurrent requests for the same uncached key may result in multiple
42
- * fetcher calls. For production use cases requiring request deduplication,
43
- * consider wrapping the cache with a promise-based deduplication layer.
43
+ * Concurrent requests for the same uncached key are deduplicated via an
44
+ * internal in-flight Promise map: only the first call invokes the fetcher,
45
+ * and subsequent callers receive the same Promise.
44
46
  *
45
47
  * @example
46
48
  * ```typescript
@@ -55,12 +57,14 @@ export interface CacheStats {
55
57
  */
56
58
  export class MetadataCache {
57
59
  private cache: Map<string, CachedSchema>;
60
+ private inflight: Map<string, Promise<unknown>>;
58
61
  private maxSize: number;
59
62
  private ttl: number;
60
63
  private stats: {
61
64
  hits: number;
62
65
  misses: number;
63
66
  evictions: number;
67
+ coalesced: number;
64
68
  };
65
69
 
66
70
  /**
@@ -72,12 +76,14 @@ export class MetadataCache {
72
76
  */
73
77
  constructor(options: { maxSize?: number; ttl?: number } = {}) {
74
78
  this.cache = new Map();
79
+ this.inflight = new Map();
75
80
  this.maxSize = options.maxSize || 100;
76
81
  this.ttl = options.ttl || 5 * 60 * 1000; // 5 minutes default
77
82
  this.stats = {
78
83
  hits: 0,
79
84
  misses: 0,
80
85
  evictions: 0,
86
+ coalesced: 0,
81
87
  };
82
88
  }
83
89
 
@@ -113,14 +119,34 @@ export class MetadataCache {
113
119
  }
114
120
  }
115
121
 
116
- // Cache miss - fetch the data
122
+ // Cache miss - dedupe concurrent fetches for the same key
123
+ const existing = this.inflight.get(key);
124
+ if (existing) {
125
+ this.stats.coalesced++;
126
+ return existing as Promise<T>;
127
+ }
128
+
117
129
  this.stats.misses++;
118
- const data = await fetcher();
130
+ const promise = (async () => {
131
+ try {
132
+ const data = await fetcher();
133
+ this.set(key, data);
134
+ return data;
135
+ } finally {
136
+ this.inflight.delete(key);
137
+ }
138
+ })();
139
+ this.inflight.set(key, promise as Promise<unknown>);
140
+ return promise;
141
+ }
119
142
 
120
- // Store in cache
143
+ /**
144
+ * Prime the cache with a pre-fetched value. Useful when a bulk endpoint
145
+ * (e.g. list of all object schemas) returns data that would otherwise
146
+ * be fetched again per item.
147
+ */
148
+ prime(key: string, data: unknown): void {
121
149
  this.set(key, data);
122
-
123
- return data;
124
150
  }
125
151
 
126
152
  /**
@@ -178,10 +204,12 @@ export class MetadataCache {
178
204
  */
179
205
  clear(): void {
180
206
  this.cache.clear();
207
+ this.inflight.clear();
181
208
  this.stats = {
182
209
  hits: 0,
183
210
  misses: 0,
184
211
  evictions: 0,
212
+ coalesced: 0,
185
213
  };
186
214
  }
187
215
 
@@ -200,6 +228,7 @@ export class MetadataCache {
200
228
  hits: this.stats.hits,
201
229
  misses: this.stats.misses,
202
230
  evictions: this.stats.evictions,
231
+ coalesced: this.stats.coalesced,
203
232
  hitRate: hitRate,
204
233
  };
205
234
  }
@@ -7,7 +7,13 @@
7
7
  */
8
8
 
9
9
  import { describe, it, expect, beforeEach, vi } from 'vitest';
10
- import { ObjectStackAdapter, ConnectionState, ConnectionStateEvent, BatchProgressEvent } from './index';
10
+ import {
11
+ ObjectStackAdapter,
12
+ ConnectionState,
13
+ ConnectionStateEvent,
14
+ BatchProgressEvent,
15
+ clearSharedDiscoveryCache,
16
+ } from './index';
11
17
 
12
18
  describe('Connection State Monitoring', () => {
13
19
  let adapter: ObjectStackAdapter;
@@ -100,6 +106,10 @@ describe('Batch Progress Events', () => {
100
106
  });
101
107
 
102
108
  describe('getDiscovery', () => {
109
+ beforeEach(() => {
110
+ clearSharedDiscoveryCache();
111
+ });
112
+
103
113
  it('should return discoveryInfo from the underlying client after connect', async () => {
104
114
  const mockDiscovery = {
105
115
  name: 'test-server',
@@ -110,32 +120,69 @@ describe('getDiscovery', () => {
110
120
  },
111
121
  };
112
122
 
123
+ const fetchImpl = vi.fn(async () =>
124
+ ({
125
+ ok: true,
126
+ json: async () => ({ success: true, data: mockDiscovery }),
127
+ }) as unknown as Response,
128
+ );
129
+
113
130
  const adapter = new ObjectStackAdapter({
114
131
  baseUrl: 'http://localhost:3000',
115
132
  autoReconnect: false,
133
+ fetch: fetchImpl,
116
134
  });
117
135
 
118
- // Mock the underlying client's connect method and discoveryInfo property
119
- const client = adapter.getClient();
120
- vi.spyOn(client, 'connect').mockResolvedValue(mockDiscovery as any);
121
- // Simulate what connect() does: sets discoveryInfo
122
- (client as any).discoveryInfo = mockDiscovery;
136
+ await adapter.connect();
123
137
 
124
138
  const discovery = await adapter.getDiscovery();
125
139
  expect(discovery).toEqual(mockDiscovery);
126
140
  expect((discovery as any)?.services?.auth?.enabled).toBe(false);
141
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
142
+ expect(fetchImpl.mock.calls[0][0]).toContain('/api/v1/discovery');
127
143
  });
128
144
 
129
145
  it('should return null when connection fails', async () => {
146
+ const fetchImpl = vi.fn(async () => {
147
+ throw new Error('Connection failed');
148
+ });
149
+
130
150
  const adapter = new ObjectStackAdapter({
131
151
  baseUrl: 'http://localhost:3000',
132
152
  autoReconnect: false,
153
+ fetch: fetchImpl as any,
133
154
  });
134
155
 
135
- const client = adapter.getClient();
136
- vi.spyOn(client, 'connect').mockRejectedValue(new Error('Connection failed'));
156
+ await expect(adapter.connect()).rejects.toThrow();
137
157
 
138
158
  const discovery = await adapter.getDiscovery();
139
159
  expect(discovery).toBeNull();
140
160
  });
161
+
162
+ it('should share a single discovery fetch across adapters with the same baseUrl', async () => {
163
+ const mockDiscovery = { name: 'shared', version: '1.0.0' };
164
+ const fetchImpl = vi.fn(async () =>
165
+ ({
166
+ ok: true,
167
+ json: async () => ({ success: true, data: mockDiscovery }),
168
+ }) as unknown as Response,
169
+ );
170
+
171
+ const a1 = new ObjectStackAdapter({
172
+ baseUrl: 'http://localhost:3000',
173
+ autoReconnect: false,
174
+ fetch: fetchImpl,
175
+ });
176
+ const a2 = new ObjectStackAdapter({
177
+ baseUrl: 'http://localhost:3000',
178
+ autoReconnect: false,
179
+ fetch: fetchImpl,
180
+ });
181
+
182
+ await Promise.all([a1.connect(), a2.connect()]);
183
+
184
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
185
+ expect(await a1.getDiscovery()).toEqual(mockDiscovery);
186
+ expect(await a2.getDiscovery()).toEqual(mockDiscovery);
187
+ });
141
188
  });
package/src/errors.ts CHANGED
@@ -28,8 +28,8 @@ export class ObjectStackError extends Error {
28
28
  this.name = 'ObjectStackError';
29
29
 
30
30
  // Maintains proper stack trace for where error was thrown (only in V8)
31
- if (Error.captureStackTrace) {
32
- Error.captureStackTrace(this, this.constructor);
31
+ if ((Error as any).captureStackTrace) {
32
+ (Error as any).captureStackTrace(this, this.constructor);
33
33
  }
34
34
  }
35
35
 
package/src/index.ts CHANGED
@@ -18,6 +18,38 @@ import {
18
18
  createErrorFromResponse,
19
19
  } from './errors';
20
20
 
21
+ // Module-level discovery cache. Multiple ObjectStackAdapter instances pointed
22
+ // at the same baseUrl (e.g. ConditionalAuthWrapper's throwaway adapter +
23
+ // AdapterProvider's main adapter) would otherwise each fire `/discovery`. By
24
+ // keying on baseUrl we collapse them to a single network round trip per origin.
25
+ const discoveryCache = new Map<string, Promise<unknown>>();
26
+
27
+ /**
28
+ * Fetch the server `discovery` document once per (baseUrl) and reuse the
29
+ * resulting Promise. Used by `ObjectStackAdapter.connect()` (and any caller
30
+ * that wants the discovery payload without spinning up a new client).
31
+ */
32
+ export async function getSharedDiscovery(
33
+ baseUrl: string,
34
+ fetcher: () => Promise<unknown>,
35
+ ): Promise<unknown> {
36
+ const key = baseUrl || '<default>';
37
+ const cached = discoveryCache.get(key);
38
+ if (cached) return cached;
39
+ const p = fetcher().catch((err) => {
40
+ // Allow retry on failure
41
+ discoveryCache.delete(key);
42
+ throw err;
43
+ });
44
+ discoveryCache.set(key, p);
45
+ return p;
46
+ }
47
+
48
+ /** Test/dev helper to drop the cache (e.g. on logout or origin change). */
49
+ export function clearSharedDiscoveryCache(): void {
50
+ discoveryCache.clear();
51
+ }
52
+
21
53
  /**
22
54
  * Connection state for monitoring
23
55
  */
@@ -88,6 +120,7 @@ export type { FileUploadResult } from '@object-ui/types';
88
120
  export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
89
121
  private client: ObjectStackClient;
90
122
  private connected: boolean = false;
123
+ private connectPromise: Promise<void> | null = null;
91
124
  private metadataCache: MetadataCache;
92
125
  private connectionState: ConnectionState = 'disconnected';
93
126
  private connectionStateListeners: ConnectionStateListener[] = [];
@@ -127,11 +160,44 @@ export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
127
160
  * Call this before making requests or it will auto-connect on first request.
128
161
  */
129
162
  async connect(): Promise<void> {
130
- if (!this.connected) {
131
- this.setConnectionState('connecting');
132
-
163
+ if (this.connected) return;
164
+ // Dedupe concurrent connect() calls — without this, every component
165
+ // that mounts on first paint can trigger an independent discovery
166
+ // request before the first one completes.
167
+ if (this.connectPromise) return this.connectPromise;
168
+
169
+ this.setConnectionState('connecting');
170
+ this.connectPromise = (async () => {
133
171
  try {
134
- await this.client.connect();
172
+ // Use the module-level discovery cache so multiple adapter instances
173
+ // (or React StrictMode double-mounts) at the same baseUrl share a
174
+ // single network round trip. We inject the result into the client's
175
+ // private `discoveryInfo` field to avoid client.connect() re-fetching.
176
+ const baseUrl = this.baseUrl || '';
177
+ const discoveryUrl = baseUrl
178
+ ? `${baseUrl.replace(/\/$/, '')}/api/v1/discovery`
179
+ : '/api/v1/discovery';
180
+
181
+ const data = await getSharedDiscovery(baseUrl, async () => {
182
+ const res = await this.fetchImpl(discoveryUrl, {
183
+ method: 'GET',
184
+ headers: this.token
185
+ ? { Authorization: `Bearer ${this.token}` }
186
+ : undefined,
187
+ });
188
+ if (!res.ok) {
189
+ throw new Error(`discovery ${res.status} ${res.statusText}`);
190
+ }
191
+ const body = await res.json();
192
+ return body && typeof body.success === 'boolean' && 'data' in body
193
+ ? body.data
194
+ : body;
195
+ });
196
+
197
+ // Prime the underlying client's cached discovery so capability/route
198
+ // helpers continue to work without a redundant fetch.
199
+ (this.client as unknown as { discoveryInfo?: unknown }).discoveryInfo = data;
200
+
135
201
  this.connected = true;
136
202
  this.reconnectAttempts = 0;
137
203
  this.setConnectionState('connected');
@@ -142,17 +208,20 @@ export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
142
208
  undefined,
143
209
  { originalError: error }
144
210
  );
145
-
211
+
146
212
  this.setConnectionState('error', connectionError);
147
-
213
+
148
214
  // Attempt auto-reconnect if enabled
149
215
  if (this.autoReconnect && this.reconnectAttempts < this.maxReconnectAttempts) {
150
216
  await this.attemptReconnect();
151
217
  } else {
152
218
  throw connectionError;
153
219
  }
220
+ } finally {
221
+ this.connectPromise = null;
154
222
  }
155
- }
223
+ })();
224
+ return this.connectPromise;
156
225
  }
157
226
 
158
227
  /**
@@ -582,9 +651,14 @@ export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
582
651
  }
583
652
  }
584
653
 
585
- // Filter
586
- if (params.$filter) {
587
- queryParams.set('filter', JSON.stringify(params.$filter));
654
+ // Filter — drop empty arrays/objects so we don't send `?filter=%5B%5D`
655
+ if (params.$filter !== undefined && params.$filter !== null) {
656
+ const isEmpty = Array.isArray(params.$filter)
657
+ ? params.$filter.length === 0
658
+ : typeof params.$filter === 'object' && Object.keys(params.$filter).length === 0;
659
+ if (!isEmpty) {
660
+ queryParams.set('filter', JSON.stringify(params.$filter));
661
+ }
588
662
  }
589
663
 
590
664
  const baseUrl = this.baseUrl.replace(/\/$/, '');
@@ -632,13 +706,19 @@ export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
632
706
  options.select = params.$select;
633
707
  }
634
708
 
635
- // Filtering - convert to ObjectStack FilterNode AST format
636
- if (params.$filter) {
637
- if (Array.isArray(params.$filter)) {
638
- // Assume active AST format if it's already an array
639
- options.filters = params.$filter;
640
- } else {
641
- options.filters = convertFiltersToAST(params.$filter);
709
+ // Filtering - convert to ObjectStack FilterNode AST format. Treat empty
710
+ // arrays/objects as "no filter" to avoid emitting `filter=[]` over the wire.
711
+ if (params.$filter !== undefined && params.$filter !== null) {
712
+ const isEmpty = Array.isArray(params.$filter)
713
+ ? params.$filter.length === 0
714
+ : typeof params.$filter === 'object' && Object.keys(params.$filter).length === 0;
715
+ if (!isEmpty) {
716
+ if (Array.isArray(params.$filter)) {
717
+ // Assume active AST format if it's already an array
718
+ options.filters = params.$filter;
719
+ } else {
720
+ options.filters = convertFiltersToAST(params.$filter);
721
+ }
642
722
  }
643
723
  }
644
724
 
@@ -829,20 +909,44 @@ export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
829
909
  await this.connect();
830
910
 
831
911
  try {
912
+ // Build measure name in the format expected by the backend analytics
913
+ // service (memory-analytics / cube). For 'count' the measure key is
914
+ // simply 'count'; for other aggregation functions it follows the
915
+ // convention `${field}_${function}` (e.g. 'amount_sum').
916
+ const measureName = params.function === 'count'
917
+ ? 'count'
918
+ : `${params.field}_${params.function}`;
919
+
832
920
  const payload: Record<string, unknown> = {
833
- object: resource,
834
- measures: [{ field: params.field, function: params.function }],
835
- dimensions: [params.groupBy],
921
+ cube: resource,
922
+ measures: [measureName],
923
+ // When groupBy is '_all' no dimensions are needed (single-bucket).
924
+ dimensions: params.groupBy && params.groupBy !== '_all' ? [params.groupBy] : [],
836
925
  };
837
926
  if (params.filter) {
838
927
  payload.filters = params.filter;
839
928
  }
840
929
 
841
930
  const data = await this.client.analytics.query(payload);
842
- if (Array.isArray(data)) return data;
843
- if (data?.data && Array.isArray(data.data)) return data.data;
844
- if (data?.results && Array.isArray(data.results)) return data.results;
845
- return [];
931
+ const rawRows: any[] = Array.isArray(data) ? data
932
+ : data?.rows && Array.isArray(data.rows) ? data.rows
933
+ : data?.data && Array.isArray(data.data) ? data.data
934
+ : data?.data?.rows && Array.isArray(data.data.rows) ? data.data.rows
935
+ : data?.results && Array.isArray(data.results) ? data.results
936
+ : [];
937
+
938
+ // Map measure keys back to the original field name so that consumers
939
+ // (ObjectChart, DashboardRenderer, etc.) can access values by field name.
940
+ // This includes count → field (e.g. 'count' → 'amount') to match the
941
+ // output format of aggregateClientSide() which always uses params.field.
942
+ return rawRows.map((row: any) => {
943
+ const mapped = { ...row };
944
+ if (measureName !== params.field && measureName in mapped) {
945
+ mapped[params.field] = mapped[measureName];
946
+ delete mapped[measureName];
947
+ }
948
+ return mapped;
949
+ });
846
950
  } catch {
847
951
  // If the analytics endpoint is not available, fall back to
848
952
  // find() + client-side aggregation