vchunikhin commented on code in PR #22140:
URL: https://github.com/apache/beam/pull/22140#discussion_r912786314


##########
playground/backend/cmd/server/server.go:
##########
@@ -143,6 +168,23 @@ func setupExamplesCatalog(ctx context.Context, 
cacheService cache.Cache, bucketN
        return nil
 }
 
+// setupDBStructure initializes the data structure
+func setupDBStructure(ctx context.Context, db db.Database, appEnv 
*environment.ApplicationEnvs, props *environment.Properties) error {
+       versions := []schema.Version{new(migration.InitialStructure)}
+       dbSchema := schema.New(ctx, db, appEnv, props, versions)
+       actualSchemaVersion, err := dbSchema.InitiateData()
+       if err != nil {
+               return err
+       }
+       if actualSchemaVersion == "" {

Review Comment:
   We don't want to have the schema version as empty string because of 
developer's mistake



##########
playground/backend/build.gradle.kts:
##########
@@ -40,17 +40,45 @@ task("tidy") {
   }
 }
 
-task("test") {
-  group = "verification"
-  description = "Test the backend"
-  doLast {
-    exec {
-      executable("go")
-      args("test", "./...")
+val startDatastoreEmulator by tasks.registering {
+    doFirst {
+        val process = ProcessBuilder()

Review Comment:
   Using ProcessBuilder allows us to wait the datastore emulator running before 
the process will be end



##########
playground/backend/internal/db/datastore/datastore_db.go:
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package datastore
+
+import (
+       "beam.apache.org/playground/backend/internal/db/entity"
+       "beam.apache.org/playground/backend/internal/logger"
+       "beam.apache.org/playground/backend/internal/utils"
+       "cloud.google.com/go/datastore"
+       "context"
+       "fmt"
+       "time"
+)
+
+const (
+       Namespace = "Playground"

Review Comment:
   We want to have a separate namespace for playground entities



##########
playground/backend/internal/db/datastore/datastore_db.go:
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package datastore
+
+import (
+       "beam.apache.org/playground/backend/internal/db/entity"
+       "beam.apache.org/playground/backend/internal/logger"
+       "beam.apache.org/playground/backend/internal/utils"
+       "cloud.google.com/go/datastore"
+       "context"
+       "fmt"
+       "time"
+)
+
+const (
+       Namespace = "Playground"
+
+       SnippetKind = "pg_snippets"
+       SchemaKind  = "pg_schema_versions"
+       SdkKind     = "pg_sdks"
+       FileKind    = "pg_files"
+)
+
+type Datastore struct {
+       Client *datastore.Client
+}
+
+func New(ctx context.Context, projectId string) (*Datastore, error) {
+       client, err := datastore.NewClient(ctx, projectId)
+       if err != nil {
+               logger.Errorf("Datastore: connection to store: error during 
connection, err: %s\n", err.Error())
+               return nil, err
+       }
+
+       return &Datastore{Client: client}, nil
+}
+
+// PutSnippet puts the snippet entity to datastore
+func (d *Datastore) PutSnippet(ctx context.Context, snipId string, snip 
*entity.Snippet) error {
+       if snip == nil {
+               logger.Errorf("Datastore: PutSnippet(): snippet is nil")
+               return nil
+       }
+       snipKey := utils.GetNameKey(SnippetKind, snipId, Namespace, nil)
+       tx, err := d.Client.NewTransaction(ctx)
+       if err != nil {
+               logger.Errorf("Datastore: PutSnippet(): error during the 
transaction creating, err: %s\n", err.Error())
+               return err
+       }
+       if _, err = tx.Put(snipKey, snip.Snippet); err != nil {
+               if rollBackErr := tx.Rollback(); rollBackErr != nil {
+                       err = rollBackErr
+               }
+               logger.Errorf("Datastore: PutSnippet(): error during the 
snippet entity saving, err: %s\n", err.Error())
+               return err
+       }
+
+       var fileKeys []*datastore.Key
+       for index := range snip.Files {
+               fileId := fmt.Sprintf("%s_%d", snipId, index)
+               fileKeys = append(fileKeys, utils.GetNameKey(FileKind, fileId, 
Namespace, nil))
+       }
+
+       if _, err = tx.PutMulti(fileKeys, snip.Files); err != nil {
+               if rollBackErr := tx.Rollback(); rollBackErr != nil {
+                       err = rollBackErr
+               }
+               logger.Errorf("Datastore: PutSnippet(): error during the file 
entity saving, err: %s\n", err.Error())
+               return err
+       }
+
+       if _, err = tx.Commit(); err != nil {
+               logger.Errorf("Datastore: PutSnippet(): error during the 
transaction committing, err: %s\n", err.Error())
+               return err
+       }
+
+       return nil
+}
+
+// GetSnippet returns the snippet entity by identifier
+func (d *Datastore) GetSnippet(ctx context.Context, id string) 
(*entity.SnippetEntity, error) {
+       key := utils.GetNameKey(SnippetKind, id, Namespace, nil)
+       snip := new(entity.SnippetEntity)
+       tx, err := d.Client.NewTransaction(ctx)

Review Comment:
   Datastore transaction helps to provide extra data consistency and atomicity



##########
playground/backend/internal/db/datastore/datastore_db.go:
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package datastore
+
+import (
+       "beam.apache.org/playground/backend/internal/db/entity"
+       "beam.apache.org/playground/backend/internal/logger"
+       "beam.apache.org/playground/backend/internal/utils"
+       "cloud.google.com/go/datastore"
+       "context"
+       "fmt"
+       "time"
+)
+
+const (
+       Namespace = "Playground"
+
+       SnippetKind = "pg_snippets"
+       SchemaKind  = "pg_schema_versions"
+       SdkKind     = "pg_sdks"
+       FileKind    = "pg_files"
+)
+
+type Datastore struct {
+       Client *datastore.Client
+}
+
+func New(ctx context.Context, projectId string) (*Datastore, error) {
+       client, err := datastore.NewClient(ctx, projectId)
+       if err != nil {
+               logger.Errorf("Datastore: connection to store: error during 
connection, err: %s\n", err.Error())
+               return nil, err
+       }
+
+       return &Datastore{Client: client}, nil
+}
+
+// PutSnippet puts the snippet entity to datastore
+func (d *Datastore) PutSnippet(ctx context.Context, snipId string, snip 
*entity.Snippet) error {
+       if snip == nil {
+               logger.Errorf("Datastore: PutSnippet(): snippet is nil")
+               return nil
+       }
+       snipKey := utils.GetNameKey(SnippetKind, snipId, Namespace, nil)
+       tx, err := d.Client.NewTransaction(ctx)

Review Comment:
   Datastore transaction helps to provide extra data consistency



##########
playground/backend/internal/db/datastore/datastore_db.go:
##########
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package datastore
+
+import (
+       "beam.apache.org/playground/backend/internal/db/entity"
+       "beam.apache.org/playground/backend/internal/logger"
+       "beam.apache.org/playground/backend/internal/utils"
+       "cloud.google.com/go/datastore"
+       "context"
+       "fmt"
+       "time"
+)
+
+const (
+       Namespace = "Playground"
+
+       SnippetKind = "pg_snippets"
+       SchemaKind  = "pg_schema_versions"
+       SdkKind     = "pg_sdks"
+       FileKind    = "pg_files"
+)
+
+type Datastore struct {
+       Client *datastore.Client
+}
+
+func New(ctx context.Context, projectId string) (*Datastore, error) {
+       client, err := datastore.NewClient(ctx, projectId)
+       if err != nil {
+               logger.Errorf("Datastore: connection to store: error during 
connection, err: %s\n", err.Error())
+               return nil, err
+       }
+
+       return &Datastore{Client: client}, nil
+}
+
+// PutSnippet puts the snippet entity to datastore
+func (d *Datastore) PutSnippet(ctx context.Context, snipId string, snip 
*entity.Snippet) error {
+       if snip == nil {
+               logger.Errorf("Datastore: PutSnippet(): snippet is nil")
+               return nil
+       }
+       snipKey := utils.GetNameKey(SnippetKind, snipId, Namespace, nil)
+       tx, err := d.Client.NewTransaction(ctx)
+       if err != nil {
+               logger.Errorf("Datastore: PutSnippet(): error during the 
transaction creating, err: %s\n", err.Error())
+               return err
+       }
+       if _, err = tx.Put(snipKey, snip.Snippet); err != nil {
+               if rollBackErr := tx.Rollback(); rollBackErr != nil {
+                       err = rollBackErr
+               }
+               logger.Errorf("Datastore: PutSnippet(): error during the 
snippet entity saving, err: %s\n", err.Error())
+               return err
+       }
+
+       var fileKeys []*datastore.Key
+       for index := range snip.Files {
+               fileId := fmt.Sprintf("%s_%d", snipId, index)
+               fileKeys = append(fileKeys, utils.GetNameKey(FileKind, fileId, 
Namespace, nil))
+       }
+
+       if _, err = tx.PutMulti(fileKeys, snip.Files); err != nil {
+               if rollBackErr := tx.Rollback(); rollBackErr != nil {
+                       err = rollBackErr
+               }
+               logger.Errorf("Datastore: PutSnippet(): error during the file 
entity saving, err: %s\n", err.Error())
+               return err
+       }
+
+       if _, err = tx.Commit(); err != nil {
+               logger.Errorf("Datastore: PutSnippet(): error during the 
transaction committing, err: %s\n", err.Error())
+               return err
+       }
+
+       return nil
+}
+
+// GetSnippet returns the snippet entity by identifier
+func (d *Datastore) GetSnippet(ctx context.Context, id string) 
(*entity.SnippetEntity, error) {
+       key := utils.GetNameKey(SnippetKind, id, Namespace, nil)
+       snip := new(entity.SnippetEntity)
+       tx, err := d.Client.NewTransaction(ctx)
+       if err != nil {
+               logger.Errorf("Datastore: GetSnippet(): error during the 
transaction creating, err: %s\n", err.Error())
+               return nil, err
+       }
+       if err = tx.Get(key, snip); err != nil {
+               if rollBackErr := tx.Rollback(); rollBackErr != nil {
+                       err = rollBackErr
+               }
+               logger.Errorf("Datastore: GetSnippet(): error during snippet 
getting, err: %s\n", err.Error())
+               return nil, err
+       }
+       snip.LVisited = time.Now()
+       snip.VisitCount += 1
+       if _, err = tx.Put(key, snip); err != nil {
+               if rollBackErr := tx.Rollback(); rollBackErr != nil {
+                       err = rollBackErr
+               }
+               logger.Errorf("Datastore: GetSnippet(): error during snippet 
setting, err: %s\n", err.Error())
+               return nil, err
+       }
+       if _, err = tx.Commit(); err != nil {
+               logger.Errorf("Datastore: GetSnippet(): error during the 
transaction committing, err: %s\n", err.Error())
+               return nil, err
+       }
+       return snip, nil
+}
+
+// PutSchemaVersion puts the schema entity to datastore
+func (d *Datastore) PutSchemaVersion(ctx context.Context, id string, schema 
*entity.SchemaEntity) error {
+       if schema == nil {
+               logger.Errorf("Datastore: PutSchemaVersion(): schema version is 
nil")
+               return nil
+       }
+       key := utils.GetNameKey(SchemaKind, id, Namespace, nil)
+       if _, err := d.Client.Put(ctx, key, schema); err != nil {
+               logger.Errorf("Datastore: PutSchemaVersion(): error during 
entity saving, err: %s\n", err.Error())
+               return err
+       }
+       return nil
+}
+
+// PutSDKs puts the SDK entity to datastore
+func (d *Datastore) PutSDKs(ctx context.Context, sdks []*entity.SDKEntity) 
error {
+       if sdks == nil || len(sdks) == 0 {
+               logger.Errorf("Datastore: PutSDKs(): sdks are empty")
+               return nil
+       }
+       var keys []*datastore.Key
+       for _, sdk := range sdks {
+               keys = append(keys, utils.GetNameKey(SdkKind, sdk.Name, 
Namespace, nil))
+       }
+       if _, err := d.Client.PutMulti(ctx, keys, sdks); err != nil {
+               logger.Errorf("Datastore: PutSDK(): error during entity saving, 
err: %s\n", err.Error())
+               return err
+       }
+       return nil
+}
+
+//GetFiles returns the file entities by a snippet identifier
+func (d *Datastore) GetFiles(ctx context.Context, snipId string, numberOfFiles 
int) ([]*entity.FileEntity, error) {
+       if numberOfFiles == 0 {
+               logger.Errorf("The number of files must be more than zero")
+               return []*entity.FileEntity{}, nil
+       }
+       tx, err := d.Client.NewTransaction(ctx, datastore.ReadOnly)

Review Comment:
   Since we use transaction only for reading, the ReadOnly mode is used . It 
will be better for 
[performance](https://cloud.google.com/datastore/docs/concepts/transactions#read-only_transactions)



##########
playground/backend/build.gradle.kts:
##########
@@ -40,17 +40,45 @@ task("tidy") {
   }
 }
 
-task("test") {
-  group = "verification"
-  description = "Test the backend"
-  doLast {
-    exec {
-      executable("go")
-      args("test", "./...")
+val startDatastoreEmulator by tasks.registering {
+    doFirst {
+        val process = ProcessBuilder()
+            .directory(projectDir)
+            .inheritIO()
+            .command("sh", "start_datastore_emulator.sh")
+            .start()
+            .waitFor()
+        if (process == 0) {
+            println("Datastore emulator started")
+        } else {
+            println("Failed to start datastore emulator")
+        }
+    }
+}
+
+val stopDatastoreEmulator by tasks.registering {
+    doLast {
+        exec {
+            executable("sh")
+            args("stop_datastore_emulator.sh")
+        }
+    }
+}
+
+val test by tasks.registering {
+    group = "verification"
+    description = "Test the backend"
+    doLast {
+        exec {
+            executable("go")
+            args("test", "./...")
+        }
     }
-  }
 }
 
+test { dependsOn(startDatastoreEmulator) }

Review Comment:
   It needs to start the datastore emulator before running tests and stop that 
at the end of testing



##########
playground/infrastructure/proxy/allow_list.py:
##########
@@ -18,7 +18,9 @@
 ALLOWED_LIST = [
     "localhost",
     "127.0.0.1",
-    "logging.googleapis.com"
+    "logging.googleapis.com",

Review Comment:
   Since router server in charge of datastore interaction, we added more 
allowed addresses for proxy



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to