vogievetsky commented on code in PR #19547:
URL: https://github.com/apache/druid/pull/19547#discussion_r3391961584


##########
web-console/src/helpers/supervisor-conversion.ts:
##########
@@ -0,0 +1,396 @@
+/*
+ * 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 { C, F, L, SqlExpression, SqlQuery } from 'druid-query-toolkit';
+
+interface MetricSpec {
+  type: string;
+  name?: string;
+  fieldName?: string;
+  maxStringBytes?: number;
+  size?: number;
+  lgK?: number;
+  tgtHllType?: string;
+  k?: number;
+}
+
+function extraArgs(...args: [any, any][]): string {
+  const filtered = args.filter(
+    ([value, defaultValue]) => value !== undefined && value !== defaultValue,
+  );
+  if (filtered.length === 0) return '';
+  return (
+    ', ' + filtered.map(([value]) => (typeof value === 'string' ? `'${value}'` 
: value)).join(', ')
+  );
+}
+
+function metricSpecToSqlExpression(metricSpec: MetricSpec): SqlExpression | 
undefined {
+  if (metricSpec.type === 'count') {
+    return SqlExpression.parse('COUNT(*)');
+  }
+
+  if (!metricSpec.fieldName) return undefined;
+  const column = C(metricSpec.fieldName);
+
+  switch (metricSpec.type) {
+    case 'longSum':
+    case 'floatSum':
+    case 'doubleSum':
+      return F('SUM', column);
+
+    case 'longMin':
+    case 'floatMin':
+    case 'doubleMin':
+      return F('MIN', column);
+
+    case 'longMax':
+    case 'floatMax':
+    case 'doubleMax':
+      return F('MAX', column);
+
+    case 'doubleFirst':
+    case 'floatFirst':
+    case 'longFirst':
+      return F('EARLIEST', column);
+
+    case 'stringFirst':
+      return F('EARLIEST', column, L(metricSpec.maxStringBytes || 128));
+
+    case 'doubleLast':
+    case 'floatLast':
+    case 'longLast':
+      return F('LATEST', column);
+
+    case 'stringLast':
+      return F('LATEST', column, L(metricSpec.maxStringBytes || 128));
+
+    case 'thetaSketch':
+      return SqlExpression.parse(
+        `APPROX_COUNT_DISTINCT_DS_THETA(${column}${extraArgs([metricSpec.size, 
16384])})`,
+      );
+
+    case 'HLLSketchBuild':
+    case 'HLLSketchMerge':
+      return SqlExpression.parse(
+        `APPROX_COUNT_DISTINCT_DS_HLL(${column}${extraArgs(
+          [metricSpec.lgK, 12],
+          [metricSpec.tgtHllType, 'HLL_4'],
+        )})`,
+      );
+
+    case 'quantilesDoublesSketch':
+      return 
SqlExpression.parse(`DS_QUANTILES_SKETCH(${column}${extraArgs([metricSpec.k, 
128])})`);
+
+    case 'hyperUnique':
+      return F('APPROX_COUNT_DISTINCT_BUILTIN', column);
+
+    default:
+      // Unsupported: tDigestSketch, momentSketch, fixedBucketsHistogram
+      return undefined;
+  }
+}
+
+export interface SupervisorSpec {

Review Comment:
   Can we reuse the `IngestionSpec` interface here?



##########
web-console/src/dialogs/supervisor-to-sql-dialog/supervisor-to-sql-dialog.scss:
##########
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+.supervisor-to-sql-dialog {
+  width: 650px;
+
+  .error-message {
+    padding: 10px;
+    background-color: rgba(219, 55, 55, 0.15);
+    border-left: 3px solid #db3737;
+    border-radius: 3px;
+    color: #ff7373;
+  }
+
+  .bp4-form-group {

Review Comment:
   are these selectors doing anything? We use blueprint 5 not 4 so at the very 
least they should be `.bp5-...` really they should use `.#{$bp-ns}` (search for 
that usage in the code to see some examples) or possibly assign actual classes 
to these things



##########
web-console/src/dialogs/supervisor-to-sql-dialog/index.ts:
##########
@@ -0,0 +1,19 @@
+/*
+ * 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.
+ */
+
+export * from './supervisor-to-sql-dialog';

Review Comment:
   In other components we avoid adding an index file with a single export



##########
web-console/src/helpers/supervisor-conversion.spec.ts:
##########
@@ -0,0 +1,361 @@
+/*
+ * 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 { SupervisorSpec } from './supervisor-conversion';
+import { convertSupervisorToSql } from './supervisor-conversion';
+
+expect.addSnapshotSerializer({
+  test: val => typeof val === 'string',
+  print: String,
+});
+
+function wikipediaSupervisor(): SupervisorSpec {
+  return {
+    type: 'kafka',
+    spec: {
+      dataSchema: {
+        dataSource: 'wikipedia',
+        timestampSpec: {
+          column: 'timestamp',
+          format: 'iso',
+        },
+        dimensionsSpec: {
+          dimensions: [
+            'channel',
+            'user',
+            { name: 'page', type: 'string' },
+            { name: 'namespace', type: 'string' },
+          ],
+        },
+        metricsSpec: [
+          { name: 'count', type: 'count' },
+          { name: 'sum_added', type: 'longSum', fieldName: 'added' },
+        ],
+      },
+      ioConfig: {
+        topic: 'wikipedia',
+        inputSource: {
+          type: 's3',
+          uris: ['s3://my-bucket/wikipedia/data/'],
+        },
+      },
+    },
+  };
+}
+
+describe('supervisor conversion', () => {
+  describe('convertSupervisorToSql', () => {
+    it('converts a supervisor with dimensions and metrics (rollup -> GROUP 
BY)', () => {
+      const converted = convertSupervisorToSql(wikipediaSupervisor(), {
+        fileLocation: 's3://my-bucket/wikipedia/data/',
+        fileType: 'json',
+      });
+
+      expect(converted.queryString).toMatchSnapshot();

Review Comment:
   I think it would be cleaner to use `toMatchInlineSnapshot` in these files



##########
web-console/src/helpers/supervisor-conversion.ts:
##########
@@ -0,0 +1,396 @@
+/*
+ * 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 { C, F, L, SqlExpression, SqlQuery } from 'druid-query-toolkit';
+
+interface MetricSpec {

Review Comment:
   This interface already exists in 
src/druid-models/metric-spec/metric-spec.tsx it should be used here (and 
extended if needed)



##########
web-console/src/dialogs/supervisor-to-sql-dialog/supervisor-to-sql-dialog.tsx:
##########
@@ -0,0 +1,323 @@
+/*
+ * 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 {
+  Button,
+  Classes,
+  Dialog,
+  FormGroup,
+  InputGroup,
+  Intent,
+  Radio,
+  RadioGroup,
+  TextArea,
+} from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import React, { useState } from 'react';
+
+import { ExternalLink } from '../../components';
+import { convertSupervisorToSql } from '../../helpers/supervisor-conversion';
+import { Api, AppToaster } from '../../singletons';
+import { deepGet } from '../../utils';
+
+import './supervisor-to-sql-dialog.scss';
+
+interface SupervisorSpec {
+  type: string;
+  spec: {
+    dataSchema: {
+      dataSource: string;
+      timestampSpec: {
+        column: string;
+        format: string;
+      };
+      dimensionsSpec: {
+        dimensions: (string | { name: string; type: string })[];
+      };
+      metricsSpec: { name?: string; fieldName?: string; type: string }[];
+    };
+    ioConfig?: {
+      topic?: string;
+      inputSource?: {
+        type: string;
+        uris?: string[];
+        baseDir?: string;
+      };
+    };
+  };
+}
+
+export interface SupervisorToSqlDialogProps {
+  onConvert(converted: { queryString: string; queryContext: any }, 
datasource?: string): void;
+  onClose(): void;
+}
+
+export const SupervisorToSqlDialog = React.memo(function SupervisorToSqlDialog(
+  props: SupervisorToSqlDialogProps,
+) {
+  const { onConvert, onClose } = props;
+
+  const [supervisorSource, setSupervisorSource] = useState<'select' | 
'paste'>('select');
+  const [selectedSupervisor, setSelectedSupervisor] = useState<string>('');
+  const [pastedSupervisor, setPastedSupervisor] = useState<string>('');
+  const [availableSupervisors, setAvailableSupervisors] = 
useState<string[]>([]);
+  const [supervisorSpec, setSupervisorSpec] = useState<SupervisorSpec | 
undefined>();
+
+  const [fileLocation, setFileLocation] = useState<string>('');
+  const [fileType, setFileType] = useState<string>('json');
+
+  const [loading, setLoading] = useState(false);
+  const [error, setError] = useState<string | undefined>();
+
+  React.useEffect(() => {
+    void loadSupervisors();
+  }, []);
+
+  async function loadSupervisors() {
+    try {
+      const supervisors = await 
Api.instance.get<string[]>('/druid/indexer/v1/supervisor');
+      setAvailableSupervisors(supervisors.data);
+      if (supervisors.data.length > 0) {
+        setSelectedSupervisor(supervisors.data[0]);
+      }
+    } catch (e) {
+      setError(`Failed to load supervisors: ${e.message}`);
+    }
+  }
+
+  async function loadSupervisorSpec(supervisorId: string) {
+    if (!supervisorId) return;
+
+    setLoading(true);
+    setError(undefined);
+
+    try {
+      const resp = await Api.instance.get<SupervisorSpec>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}`,
+      );
+      setSupervisorSpec(resp.data);
+
+      // Auto-populate file location from ioConfig if available
+      const ioConfig = deepGet(resp.data, 'spec.ioConfig');
+      if (ioConfig?.inputSource?.uris) {
+        setFileLocation(ioConfig.inputSource.uris[0] || '');
+      } else if (ioConfig?.inputSource?.baseDir) {
+        setFileLocation(ioConfig.inputSource.baseDir);
+      }
+    } catch (e) {
+      setError(`Failed to load supervisor spec: ${e.message}`);
+    } finally {
+      setLoading(false);
+    }
+  }
+
+  function parsePastedSupervisor() {
+    if (!pastedSupervisor.trim()) {
+      // Clear any previously parsed spec so a blank/cleared paste can't 
submit a stale supervisor
+      setSupervisorSpec(undefined);
+      setError(undefined);
+      return;
+    }
+
+    try {
+      const parsed = JSON.parse(pastedSupervisor);
+      setSupervisorSpec(parsed);
+      setError(undefined);
+
+      // Auto-populate file location from ioConfig if available
+      const ioConfig = deepGet(parsed, 'spec.ioConfig');
+      if (ioConfig?.inputSource?.uris) {
+        setFileLocation(ioConfig.inputSource.uris[0] || '');
+      } else if (ioConfig?.inputSource?.baseDir) {
+        setFileLocation(ioConfig.inputSource.baseDir);
+      }
+    } catch (e) {
+      setError(`Invalid JSON: ${e.message}`);
+      setSupervisorSpec(undefined);
+    }
+  }
+
+  function handleConvert() {
+    if (!supervisorSpec) {
+      AppToaster.show({
+        message: 'No supervisor spec loaded',
+        intent: Intent.DANGER,
+      });
+      return;
+    }
+
+    if (!fileLocation) {
+      AppToaster.show({
+        message: 'Please specify a file location',
+        intent: Intent.DANGER,
+      });
+      return;
+    }
+
+    let converted: { queryString: string; queryContext: any };
+    try {
+      converted = convertSupervisorToSql(supervisorSpec, {
+        fileLocation,
+        fileType,
+      });
+    } catch (e) {
+      AppToaster.show({
+        message: `Could not convert supervisor: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+      return;
+    }
+
+    AppToaster.show({
+      message: 'Supervisor converted to SQL, please review',
+      intent: Intent.SUCCESS,
+    });
+
+    onConvert(converted, deepGet(supervisorSpec, 
'spec.dataSchema.dataSource'));
+  }
+
+  React.useEffect(() => {
+    if (supervisorSource !== 'select') return;
+    if (selectedSupervisor) {
+      void loadSupervisorSpec(selectedSupervisor);
+    } else {
+      // No supervisor selected (e.g. none available); don't keep a spec from 
paste mode around
+      setSupervisorSpec(undefined);
+    }
+  }, [selectedSupervisor, supervisorSource]);
+
+  React.useEffect(() => {
+    if (supervisorSource !== 'paste') return;
+    // Always reparse on entering paste mode or editing the text so a stale 
select-mode spec is
+    // dropped and a cleared paste disables Generate SQL
+    parsePastedSupervisor();
+  }, [pastedSupervisor, supervisorSource]);
+
+  return (
+    <Dialog
+      className="supervisor-to-sql-dialog"
+      isOpen
+      onClose={onClose}
+      title="Convert supervisor to SQL"
+      canOutsideClickClose={false}
+    >
+      <div className={Classes.DIALOG_BODY}>
+        <p>
+          Convert a streaming supervisor specification to an MSQ (Multi-Stage 
Query) ingestion SQL
+          statement.{' '}

Review Comment:
   I feel like this text should make it very clear that the resulting SQL 
statement is a one shot thing and will not be streaming.



##########
web-console/src/helpers/supervisor-conversion.ts:
##########
@@ -0,0 +1,396 @@
+/*
+ * 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 { C, F, L, SqlExpression, SqlQuery } from 'druid-query-toolkit';
+
+interface MetricSpec {
+  type: string;
+  name?: string;
+  fieldName?: string;
+  maxStringBytes?: number;
+  size?: number;
+  lgK?: number;
+  tgtHllType?: string;
+  k?: number;
+}
+
+function extraArgs(...args: [any, any][]): string {
+  const filtered = args.filter(
+    ([value, defaultValue]) => value !== undefined && value !== defaultValue,
+  );
+  if (filtered.length === 0) return '';
+  return (
+    ', ' + filtered.map(([value]) => (typeof value === 'string' ? `'${value}'` 
: value)).join(', ')
+  );
+}
+
+function metricSpecToSqlExpression(metricSpec: MetricSpec): SqlExpression | 
undefined {

Review Comment:
   This function is a metric spec utility and should live in 
src/druid-models/metric-spec/metric-spec.tsx



-- 
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