forked from longtao.wu/droboticflow
67 lines
2.5 KiB
Go
67 lines
2.5 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
|
|
"droboticflow/internal/domain"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
func (store *MemoryStore) GetWorkflowRuntimePolicy(_ context.Context, workflowID string) (*domain.WorkflowRuntimePolicyRecord, error) {
|
|
store.mu.Lock()
|
|
defer store.mu.Unlock()
|
|
item, ok := store.workflowRuntimePolicies[workflowID]
|
|
if !ok {
|
|
return nil, nil
|
|
}
|
|
copy := clone(item)
|
|
return ©, nil
|
|
}
|
|
|
|
func (store *MemoryStore) UpdateWorkflowRuntimePolicyVersioned(_ context.Context, item domain.WorkflowRuntimePolicyRecord, expectedRevision int) (bool, error) {
|
|
store.mu.Lock()
|
|
defer store.mu.Unlock()
|
|
current, exists := store.workflowRuntimePolicies[item.WorkflowID]
|
|
if (exists && current.Revision != expectedRevision) || (!exists && expectedRevision != 0) {
|
|
return false, nil
|
|
}
|
|
store.workflowRuntimePolicies[item.WorkflowID] = clone(item)
|
|
return true, nil
|
|
}
|
|
|
|
func (store *MongoStore) GetWorkflowRuntimePolicy(ctx context.Context, workflowID string) (*domain.WorkflowRuntimePolicyRecord, error) {
|
|
var item domain.WorkflowRuntimePolicyRecord
|
|
err := store.workflowRuntimePolicies.FindOne(ctx, bson.M{"workflowId": workflowID}).Decode(&item)
|
|
if err == mongo.ErrNoDocuments {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &item, nil
|
|
}
|
|
|
|
func (store *MongoStore) UpdateWorkflowRuntimePolicyVersioned(ctx context.Context, item domain.WorkflowRuntimePolicyRecord, expectedRevision int) (bool, error) {
|
|
updated := false
|
|
e := supplierGuardedMongoWrite(ctx, store.workflowRuntimePolicies, item.ID, item, func(ctx context.Context, d bson.M) error {
|
|
var e error
|
|
updated, e = store.updateWorkflowRuntimePolicySupplierGuarded(ctx, item, expectedRevision)
|
|
return e
|
|
})
|
|
return updated, e
|
|
}
|
|
func (store *MongoStore) updateWorkflowRuntimePolicySupplierGuarded(ctx context.Context, item domain.WorkflowRuntimePolicyRecord, expectedRevision int) (bool, error) {
|
|
filter := bson.M{"workflowId": item.WorkflowID, "revision": expectedRevision}
|
|
if expectedRevision == 0 {
|
|
filter = bson.M{"workflowId": item.WorkflowID, "$or": bson.A{bson.M{"revision": 0}, bson.M{"revision": bson.M{"$exists": false}}}}
|
|
}
|
|
result, err := store.workflowRuntimePolicies.UpdateOne(ctx, filter, bson.M{"$set": item}, options.Update().SetUpsert(expectedRevision == 0))
|
|
if mongo.IsDuplicateKeyError(err) {
|
|
return false, nil
|
|
}
|
|
return err == nil && (result.ModifiedCount == 1 || result.UpsertedCount == 1), err
|
|
}
|