Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add warnings handler #1115

Merged
merged 2 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions packages/driver/src/baseClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import type {
SimpleRetryOptions,
SimpleTransactionOptions,
TransactionOptions,
WarningHandler,
} from "./options";
import { Options } from "./options";
import Event from "./primitives/event";
Expand Down Expand Up @@ -178,17 +179,20 @@ export class ClientConnectionHolder {
outputFormat: OutputFormat,
expectedCardinality: Cardinality,
): Promise<any> {
let result: any;
for (let iteration = 0; ; ++iteration) {
const conn = await this._getConnection();
try {
result = await conn.fetch(
const { result, warnings } = await conn.fetch(
query,
args,
outputFormat,
expectedCardinality,
this.options.session,
);
if (warnings.length) {
this.options.warningHandler(warnings);
}
return result;
} catch (err) {
if (
err instanceof errors.EdgeDBError &&
Expand All @@ -210,12 +214,11 @@ export class ClientConnectionHolder {
}
throw err;
}
return result;
}
}

async execute(query: string, args?: QueryArgs): Promise<void> {
return this.retryingFetch(
await this.retryingFetch(
query,
args,
OutputFormat.NONE,
Expand Down Expand Up @@ -576,6 +579,10 @@ export class Client implements Executor {
);
}

withWarningHandler(handler: WarningHandler): Client {
return new Client(this.pool, this.options.withWarningHandler(handler));
}

async ensureConnected(): Promise<this> {
await this.pool.ensureConnected();
return this;
Expand Down
82 changes: 62 additions & 20 deletions packages/driver/src/baseConn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import type { CodecsRegistry } from "./codecs/registry";
import { EmptyTupleCodec, EMPTY_TUPLE_CODEC, TupleCodec } from "./codecs/tuple";
import { versionGreaterThanOrEqual } from "./utils";
import * as errors from "./errors";
import { resolveErrorCode } from "./errors/resolve";
import { resolveErrorCode, errorFromJSON } from "./errors/resolve";
import type {
QueryOptions,
ProtocolVersion,
Expand Down Expand Up @@ -102,6 +102,7 @@ export type ParseResult = [
capabilities: number,
inCodecBuffer: Uint8Array | null,
outCodecBuffer: Uint8Array | null,
warnings: errors.EdgeDBError[],
];

export type connConstructor = new (
Expand Down Expand Up @@ -193,6 +194,17 @@ export class BaseRawConnection {
}
}

protected _readHeaders(): Record<string, string> {
const numFields = this.buffer.readInt16();
const headers: Record<string, string> = {};
for (let i = 0; i < numFields; i++) {
const key = this.buffer.readString();
const value = this.buffer.readString();
headers[key] = value;
}
return headers;
}

protected _abortWaiters(err: Error): void {
if (!this.connWaiter.done) {
this.connWaiter.setError(err);
Expand All @@ -213,15 +225,19 @@ export class BaseRawConnection {
return ret;
}

private _parseDescribeTypeMessage(): [
private _parseDescribeTypeMessage(
query: string,
): [
Cardinality,
ICodec,
ICodec,
number,
Uint8Array,
Uint8Array,
errors.EdgeDBError[],
] {
let capabilities = -1;
let warnings: errors.EdgeDBError[] = [];
if (this.isLegacyProtocol) {
const headers = this._parseHeaders();
if (headers.has(LegacyHeaderCodes.capabilities)) {
Expand All @@ -233,7 +249,14 @@ export class BaseRawConnection {
);
}
} else {
this._ignoreHeaders();
const headers = this._readHeaders();
if (headers["warnings"] != null) {
warnings = JSON.parse(headers.warnings).map((warning: any) => {
const err = errorFromJSON(warning);
(err as any)._query = query;
return err;
});
}
capabilities = Number(this.buffer.readBigInt64());
}

Expand Down Expand Up @@ -270,6 +293,7 @@ export class BaseRawConnection {
capabilities,
inTypeData,
outTypeData,
warnings,
];
}

Expand Down Expand Up @@ -591,7 +615,7 @@ export class BaseRawConnection {
capabilities,
inCodecData,
outCodecData,
] = this._parseDescribeTypeMessage();
] = this._parseDescribeTypeMessage(query);
} catch (e: any) {
error = e;
}
Expand Down Expand Up @@ -815,7 +839,7 @@ export class BaseRawConnection {
case chars.$T: {
try {
[newCard, inCodec, outCodec, capabilities] =
this._parseDescribeTypeMessage();
this._parseDescribeTypeMessage(query);
const key = this._getQueryCacheKey(
query,
outputFormat,
Expand Down Expand Up @@ -944,6 +968,7 @@ export class BaseRawConnection {
let outCodec: ICodec | null = null;
let inCodecBuf: Uint8Array | null = null;
let outCodecBuf: Uint8Array | null = null;
let warnings: errors.EdgeDBError[] = [];

while (parsing) {
if (!this.buffer.takeMessage()) {
Expand All @@ -962,7 +987,8 @@ export class BaseRawConnection {
capabilities,
inCodecBuf,
outCodecBuf,
] = this._parseDescribeTypeMessage();
warnings,
] = this._parseDescribeTypeMessage(query);
const key = this._getQueryCacheKey(
query,
outputFormat,
Expand Down Expand Up @@ -1023,6 +1049,7 @@ export class BaseRawConnection {
capabilities,
inCodecBuf,
outCodecBuf,
warnings,
];
}

Expand All @@ -1037,7 +1064,7 @@ export class BaseRawConnection {
result: any[] | WriteBuffer,
capabilitiesFlags: number = RESTRICTED_CAPABILITIES,
options?: QueryOptions,
): Promise<void> {
): Promise<errors.EdgeDBError[]> {
const wb = new WriteMessageBuffer();
wb.beginMessage(chars.$O);
wb.writeUInt16(0); // no headers
Expand Down Expand Up @@ -1068,6 +1095,7 @@ export class BaseRawConnection {

let error: Error | null = null;
let parsing = true;
let warnings: errors.EdgeDBError[] = [];

while (parsing) {
if (!this.buffer.takeMessage()) {
Expand Down Expand Up @@ -1104,8 +1132,15 @@ export class BaseRawConnection {

case chars.$T: {
try {
const [newCard, newInCodec, newOutCodec, capabilities] =
this._parseDescribeTypeMessage();
const [
newCard,
newInCodec,
newOutCodec,
capabilities,
_,
__,
_warnings,
] = this._parseDescribeTypeMessage(query);
const key = this._getQueryCacheKey(
query,
outputFormat,
Expand All @@ -1118,6 +1153,7 @@ export class BaseRawConnection {
capabilities,
]);
outCodec = newOutCodec;
warnings = _warnings;
} catch (e: any) {
error = e;
}
Expand Down Expand Up @@ -1157,6 +1193,8 @@ export class BaseRawConnection {
}
throw error;
}

return warnings;
}

private _getQueryCacheKey(
Expand Down Expand Up @@ -1194,15 +1232,16 @@ export class BaseRawConnection {
expectedCardinality: Cardinality,
state: Session,
privilegedMode = false,
): Promise<any> {
): Promise<{ result: any; warnings: errors.EdgeDBError[] }> {
if (this.isLegacyProtocol && outputFormat === OutputFormat.NONE) {
if (args != null) {
throw new errors.InterfaceError(
`arguments in execute() is not supported in this version of ` +
`EdgeDB. Upgrade to EdgeDB 2.0 or newer.`,
);
}
return this.legacyExecute(query, privilegedMode);
await this.legacyExecute(query, privilegedMode);
return { result: null, warnings: [] };
}

this._checkState();
Expand All @@ -1218,6 +1257,9 @@ export class BaseRawConnection {
expectedCardinality,
);
const ret: any[] = [];
// @ts-ignore
let _;
let warnings: errors.EdgeDBError[] = [];

if (!this.isLegacyProtocol) {
let [card, inCodec, outCodec] = this.queryCodecCache.get(key) ?? [];
Expand All @@ -1230,7 +1272,7 @@ export class BaseRawConnection {
(!inCodec && args !== null) ||
(this.stateCodec === INVALID_CODEC && state !== Session.defaults())
) {
[card, inCodec, outCodec] = await this._parse(
[card, inCodec, outCodec, _, _, _, warnings] = await this._parse(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw, I think these _ variable names are unnecessary? Maybe eslint would complain if you did this, but I think this is equivalent:

Suggested change
[card, inCodec, outCodec, _, _, _, warnings] = await this._parse(
[card, inCodec, outCodec,,,, warnings] = await this._parse(

Just a tiny nit, not even something I'm suggesting we do here, just putting it out there.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, I didn't know you could do that 🌈⭐. Though I think I prefer the underscores as it looks more intentional to me, and not that I've just typoed it.

query,
outputFormat,
expectedCardinality,
Expand All @@ -1241,7 +1283,7 @@ export class BaseRawConnection {
}

try {
await this._executeFlow(
warnings = await this._executeFlow(
query,
args,
outputFormat,
Expand All @@ -1255,7 +1297,7 @@ export class BaseRawConnection {
} catch (e) {
if (e instanceof errors.ParameterTypeMismatchError) {
[card, inCodec, outCodec] = this.queryCodecCache.get(key)!;
await this._executeFlow(
warnings = await this._executeFlow(
query,
args,
outputFormat,
Expand Down Expand Up @@ -1304,26 +1346,26 @@ export class BaseRawConnection {
}

if (outputFormat === OutputFormat.NONE) {
return;
return { result: null, warnings };
}
if (expectOne) {
if (requiredOne && !ret.length) {
throw new errors.NoDataError("query returned no data");
} else {
return ret[0] ?? (asJson ? "null" : null);
return { result: ret[0] ?? (asJson ? "null" : null), warnings };
}
} else {
if (ret && ret.length) {
if (asJson) {
return ret[0];
return { result: ret[0], warnings };
} else {
return ret;
return { result: ret, warnings };
}
} else {
if (asJson) {
return "[]";
return { result: "[]", warnings };
} else {
return ret;
return { result: ret, warnings };
}
}
}
Expand Down
Loading