michael-s-molina commented on code in PR #39171:
URL: https://github.com/apache/superset/pull/39171#discussion_r3561220236


##########
superset-frontend/src/core/storage/persistentState.test.ts:
##########
@@ -0,0 +1,249 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { SupersetClient } from '@superset-ui/core';
+import { createPersistentState } from './persistentState';
+
+jest.mock('@superset-ui/core', () => ({
+  SupersetClient: {
+    get: jest.fn(),
+    put: jest.fn(),
+    delete: jest.fn(),
+  },
+}));
+
+const mockGet = SupersetClient.get as jest.Mock;
+const mockPut = SupersetClient.put as jest.Mock;
+const mockDelete = SupersetClient.delete as jest.Mock;
+
+beforeEach(() => {
+  jest.clearAllMocks();
+  mockGet.mockResolvedValue({ json: { result: null } });
+  mockPut.mockResolvedValue({});
+  mockDelete.mockResolvedValue({});
+});
+
+test('get calls correct URL with publisher/name pattern', async () => {
+  const store = createPersistentState('myorg.myext');
+  await store.get('prefs');
+  expect(mockGet).toHaveBeenCalledWith({
+    endpoint: '/api/v1/extensions/myorg/myext/storage/persistent/prefs',
+  });
+});
+
+test('get returns result from response', async () => {
+  mockGet.mockResolvedValue({ json: { result: { theme: 'dark' } } });
+  const store = createPersistentState('myorg.myext');
+  expect(await store.get('prefs')).toEqual({ theme: 'dark' });
+});
+
+test('get returns null when result is absent', async () => {
+  mockGet.mockResolvedValue({ json: {} });
+  const store = createPersistentState('myorg.myext');
+  expect(await store.get('key')).toBeNull();
+});
+
+test('set calls correct URL with value in body', async () => {
+  const store = createPersistentState('myorg.myext');
+  await store.set('prefs', { theme: 'dark' });
+  expect(mockPut).toHaveBeenCalledWith({
+    endpoint: '/api/v1/extensions/myorg/myext/storage/persistent/prefs',
+    body: JSON.stringify({
+      value: { theme: 'dark' },
+      encrypt: false,
+      codec: 'json',
+    }),
+    headers: { 'Content-Type': 'application/json' },
+  });
+});
+
+test('set passes codec from options', async () => {
+  const store = createPersistentState('myorg.myext');
+  await store.set('prefs', 'sk-...', { codec: 'pickle' });
+  expect(mockPut).toHaveBeenCalledWith({
+    endpoint: '/api/v1/extensions/myorg/myext/storage/persistent/prefs',
+    body: JSON.stringify({
+      value: 'sk-...',
+      encrypt: false,
+      codec: 'pickle',
+    }),
+    headers: { 'Content-Type': 'application/json' },
+  });

Review Comment:
   Same as the reply on the `ephemeralState.test.ts:80` thread — this test 
asserts client-side codec passthrough, not server acceptance, so it's testing 
real, intended behavior of the SDK layer.



##########
superset-frontend/src/core/storage/persistentState.ts:
##########
@@ -0,0 +1,147 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type {
+  JsonValue,
+  PersistentListOptions,
+  PersistentListResult,
+  PersistentSetOptions,
+  PersistentStorageAccessor,
+  PersistentStorageTier,
+} from '@apache-superset/core/storage';
+import { SupersetClient } from '@superset-ui/core';
+import { resolveSetPayload } from './binaryCodec';
+
+/**
+ * Create persistent state (database-backed) bound to an extension ID.
+ */
+export function createPersistentState(
+  extensionId: string,
+): PersistentStorageTier {
+  const MAX_KEY_LENGTH = 255;
+  const [publisher, name] = extensionId.split('.');
+
+  const buildUrl = (key: string, shared?: boolean): string => {
+    if (key.length > MAX_KEY_LENGTH) {
+      throw new Error(
+        `Persistent storage key must be ${MAX_KEY_LENGTH} characters or less.`,
+      );
+    }
+    const encodedPublisher = encodeURIComponent(publisher);
+    const encodedName = encodeURIComponent(name);
+    const encodedKey = encodeURIComponent(key);
+    const url = 
`/api/v1/extensions/${encodedPublisher}/${encodedName}/storage/persistent/${encodedKey}`;
+    return shared ? `${url}?shared=true` : url;
+  };
+
+  const buildListUrl = (
+    options: PersistentListOptions,
+    isShared?: boolean,
+  ): string => {
+    const encodedPublisher = encodeURIComponent(publisher);
+    const encodedName = encodeURIComponent(name);
+    const url = 
`/api/v1/extensions/${encodedPublisher}/${encodedName}/storage/persistent`;
+    const params = new URLSearchParams();
+    if (isShared) params.set('shared', 'true');
+    if (options.resourceType) params.set('resource_type', 
options.resourceType);
+    if (options.resourceUuid) params.set('resource_uuid', 
options.resourceUuid);
+    params.set('page', String(options.page));
+    params.set('page_size', String(options.pageSize));
+    const query = params.toString();
+    return query ? `${url}?${query}` : url;
+  };
+
+  const list = async <T = JsonValue>(
+    options: PersistentListOptions,
+    isShared: boolean,
+  ): Promise<PersistentListResult<T>> => {
+    const response = await SupersetClient.get({
+      endpoint: buildListUrl(options, isShared),
+    });
+    return {
+      entries: response.json?.result ?? [],
+      count: response.json?.count ?? 0,
+    };
+  };
+
+  const shared: PersistentStorageAccessor = {
+    async get<T = JsonValue>(key: string): Promise<T | null> {
+      const response = await SupersetClient.get({
+        endpoint: buildUrl(key, true),
+      });
+      return (response.json?.result ?? null) as T | null;
+    },
+    async set<T = JsonValue>(
+      key: string,
+      value: T,
+      options?: PersistentSetOptions,
+    ): Promise<void> {
+      const payload = resolveSetPayload(value, options?.codec);
+      await SupersetClient.put({
+        endpoint: buildUrl(key, true),
+        body: JSON.stringify({
+          value: payload.value,
+          encrypt: options?.encrypt ?? false,
+          codec: payload.codec,
+        }),
+        headers: { 'Content-Type': 'application/json' },
+      });
+    },
+    async list<T = JsonValue>(
+      options: PersistentListOptions,
+    ): Promise<PersistentListResult<T>> {
+      return list<T>(options, true);
+    },
+    async remove(key: string): Promise<void> {
+      await SupersetClient.delete({ endpoint: buildUrl(key, true) });
+    },
+  };
+
+  return {
+    async get<T = JsonValue>(key: string): Promise<T | null> {
+      const response = await SupersetClient.get({ endpoint: buildUrl(key) });
+      return (response.json?.result ?? null) as T | null;
+    },
+    async set<T = JsonValue>(
+      key: string,
+      value: T,
+      options?: PersistentSetOptions,
+    ): Promise<void> {
+      const payload = resolveSetPayload(value, options?.codec);
+      await SupersetClient.put({
+        endpoint: buildUrl(key),
+        body: JSON.stringify({
+          value: payload.value,
+          encrypt: options?.encrypt ?? false,
+          codec: payload.codec,
+        }),
+        headers: { 'Content-Type': 'application/json' },
+      });

Review Comment:
   Not a bug — by design. We deliberately don't duplicate the server's 
`SAFE_CODECS` allowlist on the client; the REST API is the single source of 
truth and returns a 400 for a disallowed codec. Maintaining a second copy of 
that allowlist client-side would risk drifting out of sync with the server's 
actual list.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to