Promote SchemaSourceRepresentation
[yangtools.git] / yang / yang-repo-spi / src / main / java / org / opendaylight / yangtools / yang / model / repo / spi / AbstractSchemaRepository.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.model.repo.spi;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.ArrayListMultimap;
15 import com.google.common.collect.ListMultimap;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.io.Serializable;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import org.checkerframework.checker.lock.qual.GuardedBy;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
31 import org.opendaylight.yangtools.concepts.Registration;
32 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.source.SourceRepresentation;
34 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
35 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * Abstract base class for {@link SchemaRepository} implementations. It handles registration and lookup of schema
41  * sources, subclasses need only to provide their own {@link #createEffectiveModelContextFactory()} implementation.
42  */
43 @Beta
44 public abstract class AbstractSchemaRepository implements SchemaRepository, SchemaSourceRegistry {
45     private static final Logger LOG = LoggerFactory.getLogger(AbstractSchemaRepository.class);
46
47     /*
48      * Source identifier -> representation -> provider map. We usually are looking for
49      * a specific representation of a source.
50      */
51     @GuardedBy("this")
52     private final Map<SourceIdentifier, ListMultimap<Class<? extends SourceRepresentation>,
53             SchemaSourceRegistration>> sources = new HashMap<>();
54
55     /*
56      * Schema source listeners.
57      */
58     @GuardedBy("this")
59     private final List<SchemaListenerRegistration> listeners = new ArrayList<>();
60
61     private static <T extends SourceRepresentation> ListenableFuture<T> fetchSource(
62             final SourceIdentifier sourceId, final Iterator<SchemaSourceRegistration> it) {
63         final var reg = it.next();
64         @SuppressWarnings("unchecked")
65         final var provider = (SchemaSourceProvider<T>) reg.provider();
66
67         return Futures.catchingAsync(provider.getSource(sourceId), Throwable.class, input -> {
68             LOG.debug("Failed to acquire source from {}", reg, input);
69             if (it.hasNext()) {
70                 return fetchSource(sourceId, it);
71             }
72             throw new MissingSchemaSourceException("All available providers exhausted", sourceId, input);
73         }, MoreExecutors.directExecutor());
74     }
75
76     @Override
77     public <T extends SourceRepresentation> ListenableFuture<T> getSchemaSource(final SourceIdentifier id,
78             final Class<T> representation) {
79         final ArrayList<SchemaSourceRegistration> sortedSchemaSourceRegistrations;
80
81         synchronized (this) {
82             final var srcs = sources.get(id);
83             if (srcs == null) {
84                 return immediateFailedFluentFuture(new MissingSchemaSourceException(
85                     "No providers registered for source " + id, id));
86             }
87
88             sortedSchemaSourceRegistrations = new ArrayList<>(srcs.get(representation));
89         }
90
91         // TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
92         sortedSchemaSourceRegistrations.sort(SchemaProviderCostComparator.INSTANCE);
93
94         final var regs = sortedSchemaSourceRegistrations.iterator();
95         if (!regs.hasNext()) {
96             return immediateFailedFluentFuture(new MissingSchemaSourceException(
97                 "No providers for source " + id + " representation " + representation + " available", id));
98         }
99
100         final ListenableFuture<T> fetchSourceFuture = fetchSource(id, regs);
101         // Add callback to notify cache listeners about encountered schema
102         Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
103             @Override
104             public void onSuccess(final T result) {
105                 for (var listener : listeners) {
106                     listener.getInstance().schemaSourceEncountered(result);
107                 }
108             }
109
110             @Override
111             @SuppressWarnings("checkstyle:parameterName")
112             public void onFailure(final Throwable t) {
113                 LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
114             }
115         }, MoreExecutors.directExecutor());
116
117         return fetchSourceFuture;
118     }
119
120     private synchronized void addSource(final SchemaSourceRegistration reg) {
121         final var source = reg.getInstance();
122         sources.computeIfAbsent(source.getSourceIdentifier(), ignored -> ArrayListMultimap.create())
123             .put(source.getRepresentation(), reg);
124
125         final var reps = Collections.<PotentialSchemaSource<?>>singleton(source);
126         for (var l : listeners) {
127             l.getInstance().schemaSourceRegistered(reps);
128         }
129     }
130
131     private synchronized void removeSource(final SchemaSourceRegistration reg) {
132         final var source = reg.getInstance();
133         final var m = sources.get(source.getSourceIdentifier());
134         if (m != null) {
135             m.remove(source.getRepresentation(), reg);
136
137             for (var l : listeners) {
138                 l.getInstance().schemaSourceUnregistered(source);
139             }
140
141             if (m.isEmpty()) {
142                 sources.remove(source.getSourceIdentifier());
143             }
144         }
145     }
146
147     @Override
148     public <T extends SourceRepresentation> Registration registerSchemaSource(
149             final SchemaSourceProvider<? super T> provider, final PotentialSchemaSource<T> source) {
150         final var ret = new SchemaSourceRegistration(source.cachedReference(), provider);
151         addSource(ret);
152         return ret;
153     }
154
155     @Override
156     public Registration registerSchemaSourceListener(final SchemaSourceListener listener) {
157         final var ret = new SchemaListenerRegistration(listener);
158
159         synchronized (this) {
160             final var col = new ArrayList<PotentialSchemaSource<?>>();
161             for (var m : sources.values()) {
162                 for (var r : m.values()) {
163                     col.add(r.getInstance());
164                 }
165             }
166
167             // Notify first, so translator-type listeners, who react by registering a source
168             // do not cause infinite loop.
169             listener.schemaSourceRegistered(col);
170             listeners.add(ret);
171         }
172         return ret;
173     }
174
175     private final class SchemaListenerRegistration extends AbstractObjectRegistration<SchemaSourceListener> {
176         SchemaListenerRegistration(final SchemaSourceListener listener) {
177             super(listener);
178         }
179
180         @Override
181         protected void removeRegistration() {
182             listeners.remove(this);
183         }
184     }
185
186     private final class SchemaSourceRegistration extends AbstractObjectRegistration<PotentialSchemaSource<?>> {
187         private final @NonNull SchemaSourceProvider<?> provider;
188
189         SchemaSourceRegistration(final PotentialSchemaSource<?> source, final SchemaSourceProvider<?> provider) {
190             super(source);
191             this.provider = requireNonNull(provider);
192         }
193
194         @NonNull SchemaSourceProvider<?> provider() {
195             return provider;
196         }
197
198         @Override
199         protected void removeRegistration() {
200             removeSource(this);
201         }
202     }
203
204     private static final class SchemaProviderCostComparator
205             implements Comparator<SchemaSourceRegistration>, Serializable {
206         static final SchemaProviderCostComparator INSTANCE = new SchemaProviderCostComparator();
207
208         @java.io.Serial
209         private static final long serialVersionUID = 1L;
210
211         @Override
212         public int compare(final SchemaSourceRegistration o1, final SchemaSourceRegistration o2) {
213             return o1.getInstance().getCost() - o2.getInstance().getCost();
214         }
215
216         @java.io.Serial
217         private Object readResolve() {
218             return INSTANCE;
219         }
220     }
221 }