Skip to content
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
35 changes: 35 additions & 0 deletions .github/workflows/celest_db_studio.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: celest_db_studio
on:
pull_request:
paths:
- ".github/workflows/celest_db_studio.yaml"
- "packages/celest_db_studio/**"

# Prevent duplicate runs due to Graphite
# https://graphite.dev/docs/troubleshooting#why-are-my-actions-running-twice
concurrency:
group: ${{ github.repository }}-${{ github.workflow }}-${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.sha || ''}}
cancel-in-progress: true

permissions:
contents: read

jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Git Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # 4.2.2
- name: Setup Flutter
uses: subosito/flutter-action@e938fdf56512cc96ef2f93601a5a40bde3801046 # 2.19.0
with:
cache: true
- name: Get Packages
working-directory: packages/celest_db_studio
run: dart pub upgrade
- name: Setup Chromedriver
uses: nanasess/setup-chromedriver@e93e57b843c0c92788f22483f1a31af8ee48db25 # 2.3.0
- name: Test
working-directory: packages/celest_db_studio
run: dart test --fail-fast
3 changes: 3 additions & 0 deletions packages/celest_db_studio/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/
3 changes: 3 additions & 0 deletions packages/celest_db_studio/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 1.0.0

- Initial version.
5 changes: 5 additions & 0 deletions packages/celest_db_studio/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Celest Cloud DB Studio

A wrapper over [Outerbase Studio](https://github.com/outerbase/studio) for Celest Cloud databases.

This is used by Celest CLI to provide a local database studio when running `celest start` locally.
30 changes: 30 additions & 0 deletions packages/celest_db_studio/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.

include: package:lints/recommended.yaml

# Uncomment the following section to specify additional rules.

# linter:
# rules:
# - camel_case_types

# analyzer:
# exclude:
# - path/to/excluded/files/**

# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints

# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options
31 changes: 31 additions & 0 deletions packages/celest_db_studio/bin/server.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'dart:io';

import 'package:celest_db_studio/celest_db_studio.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';

Future<void> main(List<String> args) async {
final databaseUrl = Platform.environment['DATABASE_URL'];
if (databaseUrl == null) {
print('DATABASE_URL environment variable is not set.');
exit(1);
}
final authToken = Platform.environment['DATABASE_AUTH_TOKEN'];

final dbStudio = await CelestDbStudio.create(
databaseUri: Uri.parse(databaseUrl),
authToken: authToken,
);
final handler = Pipeline()
.addMiddleware(logRequests())
.addHandler(dbStudio.call);

final port = int.parse(Platform.environment['PORT'] ?? '8080');
final server = await serve(handler, InternetAddress.loopbackIPv4, port);
print('Server listening on http://localhost:${server.port}');

await ProcessSignal.sigint.watch().first;

print('Stopping server...');
await server.close(force: true);
}
130 changes: 130 additions & 0 deletions packages/celest_db_studio/lib/celest_db_studio.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import 'dart:convert';

import 'package:celest_core/_internal.dart';
import 'package:celest_db_studio/src/driver.dart';
import 'package:celest_db_studio/src/template.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';

export 'package:celest_db_studio/src/driver.dart';

/// {@template celest_db_studio.celest_db_studio}
/// A simple server which serves an instance of Outerbase Studio as an embedded
/// iframe and responds to query requests from the iframe.
///
/// The server connects to a database using the provided [databaseUri] and
/// proxies requests from the iframe to the database.
/// {@endtemplate}
final class CelestDbStudio {
/// {@macro celest_db_studio.celest_db_studio}
static Future<CelestDbStudio> create({
String pageTitle = defaultTitle,
required Uri databaseUri,
String? authToken,
}) async {
final Driver driver;
switch (databaseUri) {
case Uri(scheme: 'libsql' || 'https' || 'http'):
driver = await HranaDriver.connect(databaseUri, jwtToken: authToken);
case Uri(scheme: 'file', path: '/:memory:'):
driver = NativeDriver.memory();
case Uri(scheme: 'file'):
driver = NativeDriver.file(databaseUri.toFilePath());
default:
throw ArgumentError.value(
databaseUri.toString(),
'databaseUri',
'Unsupported database URI scheme: ${databaseUri.scheme}. '
'Supported schemes are: libsql, https, http, file',
);
}

return CelestDbStudio.from(pageTitle: pageTitle, driver: driver);
}

CelestDbStudio.from({this.pageTitle = defaultTitle, required Driver driver})
: _driver = driver;

/// The default title of the page.
static const String defaultTitle = 'DB Studio';

/// The title of the page.
///
/// If not provided, the [defaultTitle] will be used.
final String pageTitle;

final Driver _driver;

/// The rendered HTML for the index page.
late final String _indexHtml = indexHtml
.replaceAll('{{ title }}', pageTitle)
.replaceAll('{{ script }}', indexJs);

late final Router _router =
Router()
..get('/', _index)
..get('/index.html', _index)
..post('/query', _query);

late final Handler _handler = (const Pipeline()
..addMiddleware(_corsMiddleware))
.addHandler(_router.call);

static Handler _corsMiddleware(Handler innerHandler) {
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true',
};
return (Request request) async {
if (request.method == 'OPTIONS') {
return Response.ok(null, headers: corsHeaders);
}
final response = await innerHandler(request);
return response.change(headers: corsHeaders);
};
}

/// Handles the given [request] if possible.
Future<Response> call(Request request) async {
return _handler(request);
}

/// Serves the studio HTML.
Future<Response> _index(Request request) async {
return Response.ok(_indexHtml, headers: {'Content-Type': 'text/html'});
}

/// Responds to query requests from the Outerbase Studio iframe.
Future<Response> _query(Request request) async {
final json = await JsonUtf8.decodeStream(request.read());
if (json
case {
'id': final int id,
'type': final String type,
'statements': [final String statement],
} ||
{
'id': final int id,
'type': final String type,
'statement': final String statement,
}) {
try {
final result = await _driver.execute(statement);
return Response.ok(
jsonEncode({
'type': type,
'id': id,
'data': type == 'transaction' ? [result.toJson()] : result.toJson(),
}),
headers: {'Content-Type': 'application/json'},
);
} on Object catch (e) {
return Response.internalServerError(body: e.toString());
}
} else {
return Response.badRequest(body: 'Invalid request format');
}
}
}
Loading