jiangpengcheng commented on a change in pull request #4963: URL: https://github.com/apache/openwhisk/pull/4963#discussion_r614507369
########## File path: common/scala/src/main/scala/org/apache/openwhisk/core/database/mongodb/MongoDBArtifactStore.scala ########## @@ -0,0 +1,661 @@ +/* + * 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 org.apache.openwhisk.core.database.mongodb + +import java.security.MessageDigest + +import akka.actor.ActorSystem +import akka.event.Logging.ErrorLevel +import akka.http.scaladsl.model._ +import akka.stream.ActorMaterializer +import akka.stream.scaladsl._ +import akka.util.ByteString +import com.mongodb.client.gridfs.model.GridFSUploadOptions +import org.apache.openwhisk.common.{Logging, LoggingMarkers, TransactionId} +import org.apache.openwhisk.core.database._ +import org.apache.openwhisk.core.database.StoreUtils._ +import org.apache.openwhisk.core.entity.Attachments.Attached +import org.apache.openwhisk.core.entity.{DocId, DocInfo, DocRevision, DocumentReader, UUID} +import org.apache.openwhisk.http.Messages +import org.bson.json.{JsonMode, JsonWriterSettings} +import org.mongodb.scala.bson.BsonString +import org.mongodb.scala.bson.collection.immutable.Document +import org.mongodb.scala.gridfs.{GridFSBucket, GridFSFile, MongoGridFSException} +import org.mongodb.scala.model._ +import org.mongodb.scala.{MongoClient, MongoCollection, MongoException} +import spray.json._ + +import scala.concurrent.Future +import scala.util.Try + +object MongoDBArtifactStore { + val _computed = "_computed" +} + +/** + * Basic client to put and delete artifacts in a data store. + * + * @param client the mongodb client to access database + * @param dbName the name of the database to operate on + * @param collName the name of the collection to operate on + * @param documentHandler helper class help to simulate the designDoc of CouchDB + * @param viewMapper helper class help to simulate the designDoc of CouchDB + */ +class MongoDBArtifactStore[DocumentAbstraction <: DocumentSerializer](client: MongoClient, + dbName: String, + collName: String, + documentHandler: DocumentHandler, + viewMapper: MongoDBViewMapper, + val inliningConfig: InliningConfig, + val attachmentStore: Option[AttachmentStore])( + implicit system: ActorSystem, + val logging: Logging, + jsonFormat: RootJsonFormat[DocumentAbstraction], + val materializer: ActorMaterializer, + docReader: DocumentReader) + extends ArtifactStore[DocumentAbstraction] + with DocumentProvider + with DefaultJsonProtocol + with AttachmentSupport[DocumentAbstraction] { + + import MongoDBArtifactStore._ + + protected[core] implicit val executionContext = system.dispatcher + + private val mongodbScheme = "mongodb" + val attachmentScheme: String = attachmentStore.map(_.scheme).getOrElse(mongodbScheme) + + private val database = client.getDatabase(dbName) + private val collection = getCollectionAndCreateIndexes + private val gridFSBucket = GridFSBucket(database, collName) + + private val jsonWriteSettings = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build + + // MongoDB doesn't support using `$` as the first char of field name, so below two fields needs to be encoded first + private val fieldsNeedEncode = Seq("annotations", "parameters") + + override protected[database] def put(d: DocumentAbstraction)(implicit transid: TransactionId): Future[DocInfo] = { + val asJson = d.toDocumentRecord + + val id: String = asJson.fields.getOrElse("_id", JsString.empty).convertTo[String].trim + require(!id.isEmpty, "document id must be defined") + + val (old_rev, rev) = revisionCalculate(asJson) + val docinfoStr = s"id: $id, rev: $rev" + val start = + transid.started(this, LoggingMarkers.DATABASE_SAVE, s"[PUT] '$collName' saving document: '$docinfoStr'") + + val encodedData = encodeFields(fieldsNeedEncode, asJson) + + val data = JsObject( + encodedData.fields + (_computed -> documentHandler.computedFields(asJson)) + ("_rev" -> rev.toJson)) + + val filters = + if (rev.startsWith("1-")) { + // for new document, we should get no matched document and insert new one + // if there is a matched document, that one with no _rev filed will be replaced + // if there is a document with the same id but has an _rev field, will return en E11000(conflict) error + Filters.and(Filters.eq("_id", id), Filters.not(Filters.exists("_rev"))) + } else { + // for old document, we should find a matched document and replace it + // if no matched document find and try to insert new document, mongodb will return an E11000 error + Filters.and(Filters.eq("_id", id), Filters.eq("_rev", old_rev)) + } + + val f = + collection + .findOneAndReplace( + filters, + Document(data.compactPrint), + FindOneAndReplaceOptions().upsert(true).returnDocument(ReturnDocument.AFTER)) + .toFuture() + .map { doc => + transid.finished(this, start, s"[PUT] '$collName' completed document: '$docinfoStr', document: '$doc'") + DocInfo(DocId(id), DocRevision(rev)) + } + .recover { + case t: MongoException if t.getCode == 11000 => Review comment: ok -- 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. For queries about this service, please contact Infrastructure at: us...@infra.apache.org