/* Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.

Licensed 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.
==============================================================================*/

#include "core/dag/dag_edge.h"

#include "common/threading/sync/lock.h"
#include "core/dag/dag_node.h"

namespace graphlearn {

InMemoryDagEdge::InMemoryDagEdge(const DagEdgeDef& edge_def)
    : BaseDagEdge() {
  id_ = edge_def.id();
  src_output_ = edge_def.src_output();
  dst_input_ = edge_def.dst_input();
}

void InMemoryDagEdge::Send(const ScheduleFunction& func) {
  dst_->Recv(func);
}

void InMemoryDagEdge::Recv(const ScheduleFunction& func) {
  Send(func);
}

DagEdgePtr LookupOrCreateDagEdge(const DagEdgeDef& edge_def) {
  static std::mutex mtx;
  static std::unordered_map<int32_t, DagEdgePtr> edges;

  ScopedLocker<std::mutex> _(&mtx);
  int32_t eid = edge_def.id();
  if (edges[eid]) {
    return edges[eid];
  }

  BaseDagEdge* dag_edge(new InMemoryDagEdge(edge_def));
  edges[eid].reset(dag_edge);
  return edges[eid];
}

}  // namespace graphlearn
