|
| 1 | +import { |
| 2 | + DataColumn, |
| 3 | + DataResult, |
| 4 | + DataSource, |
| 5 | + ExecuteOptions, |
| 6 | + InternalError, |
| 7 | + RequestParameter, |
| 8 | + VulcanExtensionId, |
| 9 | +} from '@vulcan-sql/core'; |
| 10 | +import { Stream } from 'stream'; |
| 11 | +import { buildSQL, convertSchemaToColumns } from './sqlBuilder'; |
| 12 | +import { mapFromKsqlDbType } from './typeMapper'; |
| 13 | +import { |
| 14 | + RestfulClient, |
| 15 | + RestfulClientOptions, |
| 16 | + QueryResponse, |
| 17 | + Header, |
| 18 | + Row, |
| 19 | + FinalMessage, |
| 20 | +} from './restfulClient'; |
| 21 | + |
| 22 | +@VulcanExtensionId('ksqldb') |
| 23 | +export class KSQLDBDataSource extends DataSource<any, any> { |
| 24 | + private logger = this.getLogger(); |
| 25 | + private clientMapping = new Map< |
| 26 | + string, |
| 27 | + { client: RestfulClient; options?: RestfulClientOptions } |
| 28 | + >(); |
| 29 | + public override async onActivate() { |
| 30 | + const profiles = this.getProfiles().values(); |
| 31 | + for (const profile of profiles) { |
| 32 | + this.logger.debug( |
| 33 | + `Initializing profile: ${profile.name} using ksqldb driver` |
| 34 | + ); |
| 35 | + const options = { |
| 36 | + ...profile.connection!, |
| 37 | + }; |
| 38 | + const client = new RestfulClient(options); |
| 39 | + this.clientMapping.set(profile.name, { client, options }); |
| 40 | + |
| 41 | + // Testing connection |
| 42 | + const isRunning = await client.checkConnectionRunning(); |
| 43 | + if (!isRunning) { |
| 44 | + throw new Error('KsqlDb server is not running'); |
| 45 | + } |
| 46 | + |
| 47 | + this.logger.debug(`Profile ${profile.name} initialized`); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public async prepare({ parameterIndex }: RequestParameter) { |
| 52 | + return `$${parameterIndex}`; |
| 53 | + } |
| 54 | + |
| 55 | + public async execute({ |
| 56 | + statement: sql, |
| 57 | + bindParams, |
| 58 | + profileName, |
| 59 | + operations, |
| 60 | + }: ExecuteOptions): Promise<DataResult> { |
| 61 | + this.checkProfileExist(profileName); |
| 62 | + const { client } = this.clientMapping.get(profileName)!; |
| 63 | + |
| 64 | + const params = Object.fromEntries(bindParams); |
| 65 | + try { |
| 66 | + const builtSQL = buildSQL(sql, operations); |
| 67 | + const data = await client.query({ |
| 68 | + query: builtSQL, |
| 69 | + query_params: params, |
| 70 | + }); |
| 71 | + return await this.getResultFromRestfulResponse(data); |
| 72 | + } catch (e) { |
| 73 | + this.logger.debug( |
| 74 | + `Errors occurred, release connection from ${profileName}` |
| 75 | + ); |
| 76 | + throw e; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + private async getResultFromRestfulResponse(data: QueryResponse[]) { |
| 81 | + const dataRowStream = new Stream.Readable({ |
| 82 | + objectMode: true, |
| 83 | + read: () => null, |
| 84 | + // automatically destroy() the stream when it emits 'finish' or errors. Node > 10.16 |
| 85 | + autoDestroy: true, |
| 86 | + }); |
| 87 | + |
| 88 | + const headerData = (data[0] as Header).header; |
| 89 | + const columns: DataColumn[] = convertSchemaToColumns(headerData.schema); |
| 90 | + // add the data row to the stream |
| 91 | + for (const innerData of data) { |
| 92 | + // format the ksqldb table response to VulcanSQL Data API |
| 93 | + // https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-rest-api/query-endpoint/#example-table-response |
| 94 | + if ((innerData as Row).row) { |
| 95 | + const rowColumns = (innerData as Row).row.columns; |
| 96 | + const outputData = rowColumns.reduce((result, value, index) => { |
| 97 | + return { ...result, [columns[index].name]: value }; |
| 98 | + }, {}); |
| 99 | + dataRowStream.push(outputData); |
| 100 | + } |
| 101 | + |
| 102 | + // the end of query result |
| 103 | + if ((innerData as FinalMessage).finalMessage) { |
| 104 | + dataRowStream.push(null); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + return { |
| 109 | + getColumns: () => { |
| 110 | + return columns.map((column) => ({ |
| 111 | + name: column.name || '', |
| 112 | + // Convert KsqlDb type to FieldDataType supported by VulcanSQL for generating the response schema in the specification, see: https://github.com/Canner/vulcan-sql/pull/78#issuecomment-1621532674 |
| 113 | + type: mapFromKsqlDbType(column.type || ''), |
| 114 | + })); |
| 115 | + }, |
| 116 | + getData: () => dataRowStream, |
| 117 | + }; |
| 118 | + } |
| 119 | + |
| 120 | + private checkProfileExist(profileName: string) { |
| 121 | + if (!this.clientMapping.has(profileName)) { |
| 122 | + throw new InternalError(`Profile instance ${profileName} not found`); |
| 123 | + } |
| 124 | + } |
| 125 | +} |
0 commit comments