• Stars
    star
    126
  • Rank 284,543 (Top 6 %)
  • Language
    Dart
  • License
    BSD 3-Clause "New...
  • Created over 10 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

High-level interfaces to Google Cloud Platform APIs

Dart CI pub package package publisher

The gcloud package provides a high level idiomatic Dart interface to some of the most widely used Google Cloud Platform services.

Google Cloud Platform support package (gcloud)

Currently the following services are supported:

  • Cloud Datastore
  • Cloud Storage
  • Cloud Pub/Sub

Status: Experimental

NOTE: This package is currently experimental and published under the labs.dart.dev pub publisher in order to solicit feedback.

For packages in the labs.dart.dev publisher we generally plan to either graduate the package into a supported publisher (dart.dev, tools.dart.dev) after a period of feedback and iteration, or discontinue the package. These packages have a much higher expected rate of API and breaking changes.

Your feedback is valuable and will help us evolve this package. For general feedback, suggestions, and comments, please file an issue in the bug tracker.

API details

The APIs in this package are all based on the generic generated APIs in the googleapis and googleapis_beta packages.

This means that the authentication model for using the APIs in this package uses the googleapis_auth package.

Note that this package is only intended for being used with the standalone VM in a server or command line application. Don't expect this package to work on the browser or in Flutter.

The code snippets below demonstrating the use of this package all assume that the following imports are present:

import 'dart:io';

import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:http/http.dart' as http;
import 'package:gcloud/db.dart';
import 'package:gcloud/storage.dart';
import 'package:gcloud/pubsub.dart';
import 'package:gcloud/service_scope.dart' as ss;
import 'package:gcloud/datastore.dart' as datastore;

Getting access to the APIs

The first step in using the APIs is to get an authenticated HTTP client and with that create API class instances for accessing the different APIs. The code below assumes that you have a Google Cloud Project called my-project with credentials for a service account from that project stored in the file my-project.json.

// Read the service account credentials from the file.
var jsonCredentials = new File('my-project.json').readAsStringSync();
var credentials = new auth.ServiceAccountCredentials.fromJson(jsonCredentials);

// Get an HTTP authenticated client using the service account credentials.
var scopes = []
    ..addAll(datastore.Datastore.Scopes)
    ..addAll(Storage.SCOPES)
    ..addAll(PubSub.SCOPES);
var client = await auth.clientViaServiceAccount(credentials, scopes);

// Instantiate objects to access Cloud Datastore, Cloud Storage
// and Cloud Pub/Sub APIs.
var db = new DatastoreDB(
    new datastore.Datastore(client, 's~my-project'));
var storage = new Storage(client, 'my-project');
var pubsub = new PubSub(client, 'my-project');

All the APIs in this package supports the use of 'service scopes'. Service scopes are described in details below.

ss.fork(() {
  // register the services in the new service scope.
  registerDbService(db);
  registerStorageService(storage);
  registerPubSubService(pubsub);

  // Run application using these services.
});

The services registered with the service scope can now be reached from within all the code running in the same service scope using the below getters.

dbService.
storageService.
pubsubService.

This way it is not necessary to pass the service objects around in your code.

Use with App Engine

The gcloud package is also integrated in the Dart appengine package. This means the gcloud services are available both via the appengine context and service scopes. The authentication required to access the Google Cloud Platform services is handled automatically.

This means that getting to the App Engine Datastore can be through either the App Engine context

var db = context.services.db;

or just using the service scope registration.

var db = dbService;

Cloud Datastore

Google Cloud Datastore provide a NoSQL, schemaless database for storing non-relational data. See the product page https://cloud.google.com/datastore/ for more information.

The Cloud Datastore API provides a mapping of Dart objects to entities stored in the Datastore. The following example shows how to annotate a class to make it possible to store instances of it in the Datastore.

@db.Kind()
class Person extends db.Model {
  @db.StringProperty()
  String name;

  @db.IntProperty()
  int age;
}

The Kind annotation tell that instances of this class can be stored. The class must also inherit from Model. Now to store an object into the Datastore create an instance and use the commit function.

var person = new Person()
    ..name = ''
    ..age = 42;
await db.commit(inserts: [person]);

The function query is used to build a Query object which can be run to perform the query.

var persons = (await db.query<Person>().run()).toList();

To fetch one or multiple existing entities, use lookup.

var key = new Person()
    ..name = 'UniqueName'
    ..age = 42
    ..parentKey = db.emptyKey;
var person = (await db.lookup<Person>([key])).single;
var people = await db.lookup<Person>([key1, key2]);

NOTE: This package include a lower level API provided through the class Datastore on top of which the DatastoreDB API is build. The main reason for this additional API level is to bridge the gap between the different APIs exposed inside App Engine and through the public REST API. We reserve the rights to modify and maybe even remove this additional layer at any time.

Cloud Storage

Google Cloud Storage provide a highly available object store (aka BLOB store). See the product page https://cloud.google.com/storage/ for more information.

In Cloud Storage the objects (BLOBs) are organized in buckets. Each bucket has a name in a global namespace. The following code creates a new bucket named my-bucket and writes the content of the file my-file.txt to the object named my-object.

var bucket = await storage.createBucket('my-bucket');
new File('my-file.txt').openRead().pipe(bucket.write('my-object'));

The following code will read back the object.

bucket.read('my-object').pipe(new File('my-file-copy.txt').openWrite());

Cloud Pub/Sub

Google Cloud Pub/Sub provides many-to-many, asynchronous messaging. See the product page https://cloud.google.com/pubsub/ for more information.

Cloud Pub/Sub uses two concepts for messaging. Topics are used if you want to send messages and subscriptions are used to subscribe to topics and receive the messages. This decouples the producer of a message from the consumer of a message.

The following code creates a topic and sends a simple test message:

var topic = await pubsub.createTopic('my-topic');
await topic.publishString('Hello, world!')

With the following code a subscription is created on the topic and a message is pulled using the subscription. A received message must be acknowledged when the consumer has processed it.

var subscription =
    await pubsub.createSubscription('my-subscription', 'my-topic');
var pullEvent = await subscription.pull();
print(pullEvent.message.asString);
await pullEvent.acknowledge();

It is also possible to receive messages using push events instead of pulling from the subscription. To do this the subscription should be configured as a push subscription with an HTTP endpoint.

await pubsub.createSubscription(
    'my-subscription',
    'my-topic',
    endpoint: Uri.parse('https://server.example.com/push'));

With this subscription all messages will be send to the URL provided in the endpoint argument. The server needs to acknowledge the reception of the message with a 200 OK reply.

Running tests

If you want to run the end-to-end tests, a Google Cloud project is required. When running these tests the following environment variables need to be set:

GCLOUD_E2E_TEST_PROJECT

The value of the environment variable GCLOUD_E2E_TEST_PROJECT is the name of the Google Cloud project to use. Authentication for testing uses Application Default Credentials locally you can provide GOOGLE_APPLICATION_CREDENTIALS or use gcloud auth application-default login.

You will also need to create indexes as follows:

gcloud --project "$GCLOUD_E2E_TEST_PROJECT" datastore indexes create test/index.yaml

More Repositories

1

sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
Dart
10,110
star
2

language

Design of the Dart language
TeX
2,652
star
3

dart-pad

An online Dart editor with support for console, web, and Flutter apps
Dart
1,702
star
4

pub

The pub command line tool
Dart
1,040
star
5

http

A composable API for making HTTP requests in Dart.
Dart
1,021
star
6

site-www

Source for Dart website
Dart
944
star
7

shelf

Web server middleware for Dart
Dart
920
star
8

build

A build system for Dart written in Dart
Dart
785
star
9

pub-dev

The pub.dev website
Dart
785
star
10

dart_style

An opinionated formatter/linter for Dart code
Dart
645
star
11

dart-vim-plugin

Syntax highlighting for Dart in Vim
Vim Script
637
star
12

mockito

Mockito-inspired mock library for Dart
Dart
632
star
13

linter

Linter for Dart.
Dart
628
star
14

samples

A collection of Dart code samples by Dart DevRel
Dart
602
star
15

test

A library for writing unit tests in Dart.
Dart
492
star
16

source_gen

Automatic source code generation for Dart
Dart
484
star
17

dartdoc

API documentation tool for Dart.
Dart
473
star
18

markdown

A Dart markdown library
Dart
444
star
19

code_builder

A fluent API for generating valid Dart source code
Dart
428
star
20

web_socket_channel

StreamChannel wrappers for WebSockets.
Dart
418
star
21

leak_tracker

A framework for memory leak tracking for Dart and Flutter applications.
Dart
387
star
22

collection

The collection package for Dart contains a number of separate libraries with utility functions and classes that makes working with collections easier.
Dart
375
star
23

ffigen

FFI binding generator
Dart
364
star
24

logging

A Dart package for debug and error logging.
Dart
332
star
25

async

A Dart package that contains tools to work with asynchronous computations.
Dart
320
star
26

wasm

Utilities for loading and running WASM modules from Dart code
Dart
309
star
27

html

Dart port of html5lib. For parsing HTML/HTML5 with Dart. Works in the client and on the server.
Dart
276
star
28

crypto

A set of cryptographic functions implemented in pure Dart.
Dart
275
star
29

path

A string-based path manipulation library.
Dart
223
star
30

args

A command-line argument parsing library for Dart.
Dart
214
star
31

webdev

A CLI for Dart web development.
Dart
212
star
32

oauth2

An OAuth2 client library for Dart.
Dart
211
star
33

pana

Package ANAlysis for Dart
Dart
205
star
34

setup-dart

A GitHub Action to install and setup a Dart SDK.
Dart
188
star
35

yaml

A Dart YAML parser.
Dart
169
star
36

jnigen

Experimental bindings generator for Java bindings through dart:ffi and JNI.
Dart
154
star
37

homebrew-dart

Dart team's official tap for homebrew.
Ruby
153
star
38

native

Dart packages related to FFI and native assets bundling.
Dart
153
star
39

http2

A HTTP/2 implementation for dart.
Dart
153
star
40

sample-pop_pop_win

"Pop, Pop, Win!" is an implementation of Minesweeper in Dart.
Dart
149
star
41

usage

A Google Analytics wrapper for command-line, web, and Flutter apps.
Dart
143
star
42

watcher

A file system watcher library for Dart.
Dart
138
star
43

mime

Dart package for working with MIME type definitions and for processing streams of MIME multipart media types.
Dart
132
star
44

stack_trace

A package for manipulating stack traces and printing them readably.
Dart
128
star
45

web

Lightweight browser API bindings built around JS static interop.
Dart
128
star
46

platform

A generic platform abstraction for Dart
Dart
125
star
47

stream_transform

Dart utility methods to create StreamTransfomer instances to manipulate Streams
Dart
123
star
48

lints

Official Dart lint rules; the core and recommended set of lints suggested by the Dart team.
Dart
116
star
49

coverage

Dart coverage data manipulation and formatting
Dart
103
star
50

sse

Dart Server Sent Events package
Dart
96
star
51

csslib

A library for parsing CSS.
Dart
95
star
52

benchmark_harness

The official benchmark harness for Dart
Dart
94
star
53

appengine

Dart support for App Engine managed VMs
Dart
93
star
54

fake_async

Fake asynchronous events for deterministic testing.
Dart
90
star
55

convert

Conversion utilities
Dart
72
star
56

matcher

A declarative API for specifying expectations.
Dart
71
star
57

json_rpc_2

A Dart implementation of the JSON-RPC 2.0 spec.
Dart
71
star
58

characters

A package for characters represented as unicode extended grapheme clusters
Dart
69
star
59

dart-docker

Docker images for the Dart programming language (https://dart.dev)
Dart
68
star
60

pub_semver

A package for working with Pub/semver-style versions and version constraints
Dart
65
star
61

i18n

A general mono-repo for Dart i18n and l10n packages.
Dart
63
star
62

cli_util

A library to help in building Dart command-line apps
Dart
60
star
63

string_scanner

A class for parsing strings using a sequence of patterns.
Dart
60
star
64

glob

Bash-style filename globbing for Dart.
Dart
56
star
65

pubspec_parse

Simple package for parsing pubspec.yaml files with a type-safe API and rich error reporting
Dart
51
star
66

pool

A class for managing a finite pool of resources.
Dart
51
star
67

stream_channel

An abstraction for two-way communication channels.
Dart
50
star
68

io

Utilities for the Dart VM's dart:io.
Dart
49
star
69

macros

A Dart mono-repo for macro development.
Dart
48
star
70

fixnum

Fixed-width integer library for Dart.
Dart
45
star
71

clock

A fakeable wrapper for dart:core clock APIs.
Dart
41
star
72

ecosystem

This repository is home to general Dart Ecosystem tools and packages.
Dart
41
star
73

http_parser

A platform-independent Dart package for parsing and serializing HTTP formats.
Dart
39
star
74

site-shared

Content shared across Dart websites
JavaScript
38
star
75

co19

A Dart language and library conformance test suite
Dart
37
star
76

typed_data

Utility functions and classes that makes working with typed data lists easier in Dart
Dart
34
star
77

source_span

A library for identifying source spans and locations.
Dart
29
star
78

tools

This repository is home to tooling related Dart packages.
Dart
29
star
79

http_multi_server

A dart:io HttpServer wrapper that handles requests from multiple servers.
Dart
28
star
80

yaml_edit

A library for YAML manipulation with comment and whitespace preservation.
Dart
27
star
81

native_synchronization

Low-level synchronization primitives built using dart:ffi.
Dart
26
star
82

os_detect

Dart multi-platform operating system identification
Dart
24
star
83

dartbug.com

The redirect service for Dart issues and bugs.
Dart
23
star
84

bazel_worker

Dart integration for Bazel build system
Dart
23
star
85

boolean_selector

A flexible syntax for boolean expressions.
Dart
23
star
86

dart-syntax-highlight

Tools and documentation for how Dart code is formatted
Dart
22
star
87

api.dart.dev

Dart API docs
Python
19
star
88

grpc_cronet

Flutter dart:grpc implementation that uses the Cronet native library.
Dart
18
star
89

dart_ci

Tools used by Dart's continuous integration (CI) testing that aren't needed by Dart SDK contributors. Mirrored from dart.googlesource.com/dart_ci. Do not land pull requests on Github.
Dart
18
star
90

source_maps

A package to programmatically manipulate source maps.
Dart
16
star
91

term_glyph

Useful glyphs and Windows-safe equivalents
Dart
16
star
92

package_config

Support for working with Package Resolution Configuration files
Dart
16
star
93

test_process

A Dart package for testing subprocesses
Dart
16
star
94

browser_launcher

Provides a standardized way to launch web browsers.
Dart
16
star
95

timing

A Dart package for tracking time spent in child operations
Dart
14
star
96

root_certificates

The set of root certificates trusted by dart:io's default SecurityContext. Taken from Mozilla's NSS library.
C++
11
star
97

test_descriptor

Provides a convenient, easy-to-read API for defining and verifying directory structures in tests
Dart
10
star
98

dartlang_project_templates

Project templates for new repos under the dart-lang organization
Dart
8
star
99

source_map_stack_trace

Convert stack traces generated by dart2js-compiled code into readable native Dart stack traces
Dart
8
star
100

.github

GitHub default community health file for dart-lang repos
7
star