forked from confluentinc/ksql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery-result.ts
162 lines (140 loc) · 4.41 KB
/
query-result.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import {
Frame,
Row,
RawRow,
QueryResult,
OutputWriter,
} from './api';
import {
MessageFrame,
DataFrame,
FlowFrame,
CloseFrame,
} from './protocol';
import {
sync,
stream,
Stream,
Subscription,
CloseMode
} from '@thi.ng/rstream';
import { filter } from '@thi.ng/transducers';
interface QueryResultHeader {
columns: string[];
columnTypes: string[];
}
const parseMessageFrame = (
messageFrame: MessageFrame
): { queryId: number, header: QueryResultHeader } => {
const { message } = messageFrame.revive();
return {
// TODO: assert structure
queryId: message['query-id'],
header: {
columns: message.cols,
columnTypes: message['col-types']
}
};
};
const toRow = (header: QueryResultHeader, data: DataFrame): Record<string, any> => {
const { payload } = data.revive();
const values = JSON.parse(payload.toString());
return header.columns.reduce((acc, k, i) => (acc[k] = values[i], acc), {});
};
const toRawRow = (header: QueryResultHeader, data: DataFrame): RawRow => {
const { payload } = data.revive();
const values = JSON.parse(payload.toString());
return { ...header, values };
};
class QueryResultImpl implements QueryResult {
queryId: number
promiseStream: Stream<[Function, Function]> = stream<[Function, Function]>()
fulfilledStream: Subscription<any, any>
closed: boolean = false
constructor(
private channelId: number,
private inputChannel: Subscription<Frame<any>, Frame<any>>,
private writeOutput: OutputWriter,
messageFrame: MessageFrame,
mapRow: boolean = true,
) {
const { queryId, header } = parseMessageFrame(messageFrame);
this.queryId = queryId;
const dataStream = inputChannel.transform(
filter((x) => x instanceof DataFrame)
);
this.fulfilledStream = sync({
src: { promise: this.promiseStream, data: dataStream },
reset: true,
all: true,
backPressure: 1000,
}).subscribe({
next: ({ promise, data }: { promise: [Function, Function], data: DataFrame }) => {
const [resolve, reject] = promise;
try {
const row = mapRow ? toRow(header, data) : toRawRow(header, data);
writeOutput(FlowFrame.encode({ channelId, val: data.bytes.length }))
resolve({ value: row, done: false });
} catch (err) {
reject(err);
}
}
});
inputChannel.subscribe({
next: (_) => setTimeout(() => this.close()), // defer parent stream close until next tick
}, filter((x) => x instanceof CloseFrame), {
closeIn: CloseMode.FIRST
});
}
[Symbol.asyncIterator](): AsyncIterator<Row> {
return {
next: () => {
if (this.closed) {
return Promise.resolve({ value: undefined, done: true });
}
return new Promise((resolve, reject) => {
this.promiseStream.next([resolve, reject]);
});
},
return: () => {
this.close();
return Promise.resolve({ value: undefined, done: true });
}
}
}
async gather() {
const acc = [];
for await (const row of this) {
acc.push(row);
}
return acc;
}
close() {
if (this.closed) {
return;
}
this.closed = true;
// flush pending
this.promiseStream.subscribe({
next: ([resolve]) => resolve({ value: undefined, done: true })
});
this.inputChannel.done();
this.promiseStream.done();
}
}
export const createPendingQueryResult = (
channelId: number,
inputChannel: Subscription<Frame<any>, Frame<any>>,
writeOutput: OutputWriter,
mapRow?: boolean
): Promise<QueryResult> => new Promise((resolve, reject) => {
// await the RequestFrame response
// TODO: reject after timeout
inputChannel.subscribe({
next: (messageFrame: MessageFrame) => {
resolve(new QueryResultImpl(channelId, inputChannel, writeOutput, messageFrame, mapRow))
}
}, filter((x) => x instanceof MessageFrame), {
closeIn: CloseMode.FIRST
});
});