Skip to content

Automatic connection reconnecting #385

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

Merged
merged 25 commits into from
Apr 3, 2025
Merged
Show file tree
Hide file tree
Changes from 16 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
48 changes: 48 additions & 0 deletions src/engines/abstract-remote.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { HttpConnectionError } from "../errors";
import { AbstractEngine } from "./abstract";

export abstract class AbstractRemoteEngine extends AbstractEngine {
protected async req_post(
body: unknown,
url?: URL,
headers_?: Record<string, string>,
): Promise<ArrayBuffer> {
const headers: Record<string, string> = {
"Content-Type": "application/cbor",
Accept: "application/cbor",
...headers_,
};

if (this.connection.namespace) {
headers["Surreal-NS"] = this.connection.namespace;
}

if (this.connection.database) {
headers["Surreal-DB"] = this.connection.database;
}

if (this.connection.token) {
headers.Authorization = `Bearer ${this.connection.token}`;
}

const raw = await fetch(`${url ?? this.connection.url}`, {
method: "POST",
headers,
body: this.encodeCbor(body),
});

const buffer = await raw.arrayBuffer();

if (raw.status === 200) {
return buffer;
}

const dec = new TextDecoder("utf-8");
throw new HttpConnectionError(
dec.decode(buffer),
raw.status,
raw.statusText,
buffer,
);
}
}
122 changes: 72 additions & 50 deletions src/engines/abstract.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,41 @@
import { type EngineDisconnected, HttpConnectionError } from "../errors";
import type {
ExportOptions,
LiveHandlerArguments,
RpcRequest,
RpcResponse,
import type { EngineDisconnected } from "../errors";
import {
convertAuth,
type AuthClient,
type ExportOptions,
type LiveHandlerArguments,
type RpcRequest,
type RpcResponse,
type ScopeAuth,
type AccessRecordAuth,
type AnyAuth,
type Token,
} from "../types";
import type { Emitter } from "../util/emitter";
import { processAuthVars } from "../util/process-auth-vars";
import type { ReconnectContext } from "../util/reconnect";

export type Engine = new (context: EngineContext) => AbstractEngine;
export type Engines = Record<string, Engine>;
export const RetryMessage: unique symbol = Symbol("RetryMessage");

export type EngineEvents = {
connecting: [];
connected: [];
reconnecting: [];
disconnected: [];
error: [Error];

[K: `rpc-${string | number}`]: [RpcResponse | EngineDisconnected];
[K: `rpc-${string | number}`]: [
RpcResponse | EngineDisconnected | typeof RetryMessage,
];
[K: `live-${string}`]: LiveHandlerArguments;
};

export enum ConnectionStatus {
Disconnected = "disconnected",
Connecting = "connecting",
Reconnecting = "reconnecting",
Connected = "connected",
Error = "error",
}
Expand All @@ -32,20 +45,24 @@ export class EngineContext {
readonly encodeCbor: (value: unknown) => ArrayBuffer;
// biome-ignore lint/suspicious/noExplicitAny: Don't know what it will return
readonly decodeCbor: (value: ArrayBufferLike) => any;
readonly reconnect: ReconnectContext;

constructor({
emitter,
encodeCbor,
decodeCbor,
reconnect,
}: {
emitter: Emitter<EngineEvents>;
encodeCbor: (value: unknown) => ArrayBuffer;
// biome-ignore lint/suspicious/noExplicitAny: Don't know what it will return
decodeCbor: (value: ArrayBufferLike) => any;
reconnect: ReconnectContext;
}) {
this.emitter = emitter;
this.encodeCbor = encodeCbor;
this.decodeCbor = decodeCbor;
this.reconnect = reconnect;
}
}

Expand Down Expand Up @@ -93,47 +110,52 @@ export abstract class AbstractEngine {
abstract export(options?: Partial<ExportOptions>): Promise<string>;
abstract import(data: string): Promise<void>;

protected async req_post(
body: unknown,
url?: URL,
headers_?: Record<string, string>,
): Promise<ArrayBuffer> {
const headers: Record<string, string> = {
"Content-Type": "application/cbor",
Accept: "application/cbor",
...headers_,
};

if (this.connection.namespace) {
headers["Surreal-NS"] = this.connection.namespace;
}

if (this.connection.database) {
headers["Surreal-DB"] = this.connection.database;
}

if (this.connection.token) {
headers.Authorization = `Bearer ${this.connection.token}`;
}

const raw = await fetch(`${url ?? this.connection.url}`, {
method: "POST",
headers,
body: this.encodeCbor(body),
});

const buffer = await raw.arrayBuffer();

if (raw.status === 200) {
return buffer;
}

const dec = new TextDecoder("utf-8");
throw new HttpConnectionError(
dec.decode(buffer),
raw.status,
raw.statusText,
buffer,
);
}
// protected authClient(): AuthClient {
// const self = this;

// return {
// async signup(vars: ScopeAuth | AccessRecordAuth): Promise<Token> {
// const parsed = processAuthVars(vars, self.connection);
// const converted = convertAuth(parsed);
// const res: RpcResponse<Token> = await self.rpc({
// method: "signup",
// params: [converted],
// });

// if (res.error) throw new ResponseError(res.error.message);
// if (!res.result) {
// throw new NoTokenReturned();
// }

// return res.result;
// }

// async signin(vars: AnyAuth): Promise<Token> {
// if (!this.connection) throw new NoActiveSocket();

// const parsed = processAuthVars(vars, this.connection.connection);
// const converted = convertAuth(parsed);
// const res = await this.rpc<Token>("signin", [converted]);

// if (res.error) throw new ResponseError(res.error.message);
// if (!res.result) {
// throw new NoTokenReturned();
// }

// return res.result;
// }

// async authenticate(token: Token): Promise<true> {
// const res = await this.rpc<string>("authenticate", [token]);
// if (res.error) throw new ResponseError(res.error.message);
// return true;
// }

// async invalidate(): Promise<true> {
// const res = await this.rpc("invalidate");
// if (res.error) throw new ResponseError(res.error.message);
// return true;
// }
// }
// }
}
9 changes: 3 additions & 6 deletions src/engines/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@ import { ConnectionUnavailable, MissingNamespaceDatabase } from "../errors";
import type { ExportOptions, RpcRequest, RpcResponse } from "../types";
import { getIncrementalID } from "../util/get-incremental-id";
import { retrieveRemoteVersion } from "../util/version-check";
import {
AbstractEngine,
ConnectionStatus,
type EngineEvents,
} from "./abstract";
import { ConnectionStatus, type EngineEvents } from "./abstract";
import { AbstractRemoteEngine } from "./abstract-remote";

const ALWAYS_ALLOW = new Set([
"signin",
Expand All @@ -20,7 +17,7 @@ const ALWAYS_ALLOW = new Set([
"query",
]);

export class HttpEngine extends AbstractEngine {
export class HttpEngine extends AbstractRemoteEngine {
connection: {
url: URL | undefined;
namespace: string | undefined;
Expand Down
Loading
Loading