LCOV - code coverage report
Current view: top level - server/account - Accounts.java (source / functions) Hit Total Coverage
Test: _coverage_report.dat Lines: 35 44 79.5 %
Date: 2022-11-19 15:00:39 Functions: 11 13 84.6 %

          Line data    Source code
       1             : // Copyright (C) 2017 The Android Open Source Project
       2             : //
       3             : // Licensed under the Apache License, Version 2.0 (the "License");
       4             : // you may not use this file except in compliance with the License.
       5             : // You may obtain a copy of the License at
       6             : //
       7             : // http://www.apache.org/licenses/LICENSE-2.0
       8             : //
       9             : // Unless required by applicable law or agreed to in writing, software
      10             : // distributed under the License is distributed on an "AS IS" BASIS,
      11             : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      12             : // See the License for the specific language governing permissions and
      13             : // limitations under the License.
      14             : 
      15             : package com.google.gerrit.server.account;
      16             : 
      17             : import static java.util.Comparator.comparing;
      18             : import static java.util.stream.Collectors.toList;
      19             : import static java.util.stream.Collectors.toSet;
      20             : 
      21             : import com.google.common.flogger.FluentLogger;
      22             : import com.google.gerrit.entities.Account;
      23             : import com.google.gerrit.entities.RefNames;
      24             : import com.google.gerrit.metrics.Description;
      25             : import com.google.gerrit.metrics.MetricMaker;
      26             : import com.google.gerrit.metrics.Timer0;
      27             : import com.google.gerrit.server.account.externalids.ExternalIds;
      28             : import com.google.gerrit.server.config.AllUsersName;
      29             : import com.google.gerrit.server.config.CachedPreferences;
      30             : import com.google.gerrit.server.config.VersionedDefaultPreferences;
      31             : import com.google.gerrit.server.git.GitRepositoryManager;
      32             : import com.google.inject.Inject;
      33             : import com.google.inject.Singleton;
      34             : import java.io.IOException;
      35             : import java.util.ArrayList;
      36             : import java.util.Collection;
      37             : import java.util.List;
      38             : import java.util.Objects;
      39             : import java.util.Optional;
      40             : import java.util.Set;
      41             : import java.util.stream.Stream;
      42             : import org.eclipse.jgit.errors.ConfigInvalidException;
      43             : import org.eclipse.jgit.lib.Repository;
      44             : 
      45             : /** Class to access accounts. */
      46             : @Singleton
      47             : public class Accounts {
      48         151 :   private static final FluentLogger logger = FluentLogger.forEnclosingClass();
      49             : 
      50             :   private final GitRepositoryManager repoManager;
      51             :   private final AllUsersName allUsersName;
      52             :   private final ExternalIds externalIds;
      53             :   private final Timer0 readSingleLatency;
      54             : 
      55             :   @Inject
      56             :   Accounts(
      57             :       GitRepositoryManager repoManager,
      58             :       AllUsersName allUsersName,
      59             :       ExternalIds externalIds,
      60         151 :       MetricMaker metricMaker) {
      61         151 :     this.repoManager = repoManager;
      62         151 :     this.allUsersName = allUsersName;
      63         151 :     this.externalIds = externalIds;
      64         151 :     this.readSingleLatency =
      65         151 :         metricMaker.newTimer(
      66             :             "notedb/read_single_account_config_latency",
      67             :             new Description("Latency for reading a single account config.")
      68         151 :                 .setCumulative()
      69         151 :                 .setUnit(Description.Units.MILLISECONDS));
      70         151 :   }
      71             : 
      72             :   public Optional<AccountState> get(Account.Id accountId)
      73             :       throws IOException, ConfigInvalidException {
      74         138 :     try (Repository repo = repoManager.openRepository(allUsersName)) {
      75         138 :       return read(repo, accountId);
      76             :     }
      77             :   }
      78             : 
      79             :   public List<AccountState> get(Collection<Account.Id> accountIds)
      80             :       throws IOException, ConfigInvalidException {
      81           0 :     List<AccountState> accounts = new ArrayList<>(accountIds.size());
      82           0 :     try (Repository repo = repoManager.openRepository(allUsersName)) {
      83           0 :       for (Account.Id accountId : accountIds) {
      84           0 :         read(repo, accountId).ifPresent(accounts::add);
      85           0 :       }
      86             :     }
      87           0 :     return accounts;
      88             :   }
      89             : 
      90             :   /**
      91             :    * Returns all accounts.
      92             :    *
      93             :    * @return all accounts
      94             :    */
      95             :   public List<AccountState> all() throws IOException {
      96           5 :     Set<Account.Id> accountIds = allIds();
      97           5 :     List<AccountState> accounts = new ArrayList<>(accountIds.size());
      98           5 :     try (Repository repo = repoManager.openRepository(allUsersName)) {
      99           5 :       for (Account.Id accountId : accountIds) {
     100             :         try {
     101           5 :           read(repo, accountId).ifPresent(accounts::add);
     102           0 :         } catch (Exception e) {
     103           0 :           logger.atSevere().withCause(e).log("Ignoring invalid account %s", accountId);
     104           5 :         }
     105           5 :       }
     106             :     }
     107           5 :     return accounts;
     108             :   }
     109             : 
     110             :   /**
     111             :    * Returns all account IDs.
     112             :    *
     113             :    * @return all account IDs
     114             :    */
     115             :   public Set<Account.Id> allIds() throws IOException {
     116          21 :     return readUserRefs().collect(toSet());
     117             :   }
     118             : 
     119             :   /**
     120             :    * Returns the first n account IDs.
     121             :    *
     122             :    * @param n the number of account IDs that should be returned
     123             :    * @return first n account IDs
     124             :    */
     125             :   public List<Account.Id> firstNIds(int n) throws IOException {
     126           0 :     return readUserRefs().sorted(comparing(Account.Id::get)).limit(n).collect(toList());
     127             :   }
     128             : 
     129             :   /**
     130             :    * Checks if any account exists.
     131             :    *
     132             :    * @return {@code true} if at least one account exists, otherwise {@code false}
     133             :    */
     134             :   public boolean hasAnyAccount() throws IOException {
     135          15 :     try (Repository repo = repoManager.openRepository(allUsersName)) {
     136          15 :       return hasAnyAccount(repo);
     137             :     }
     138             :   }
     139             : 
     140             :   public static boolean hasAnyAccount(Repository repo) throws IOException {
     141          30 :     return readUserRefs(repo).findAny().isPresent();
     142             :   }
     143             : 
     144             :   private Stream<Account.Id> readUserRefs() throws IOException {
     145          21 :     try (Repository repo = repoManager.openRepository(allUsersName)) {
     146          21 :       return readUserRefs(repo);
     147             :     }
     148             :   }
     149             : 
     150             :   private Optional<AccountState> read(Repository allUsersRepository, Account.Id accountId)
     151             :       throws IOException, ConfigInvalidException {
     152             :     AccountConfig cfg;
     153             :     CachedPreferences defaultPreferences;
     154         138 :     try (Timer0.Context ignored = readSingleLatency.start()) {
     155         138 :       cfg = new AccountConfig(accountId, allUsersName, allUsersRepository).load();
     156         138 :       defaultPreferences =
     157         138 :           CachedPreferences.fromConfig(
     158         138 :               VersionedDefaultPreferences.get(allUsersRepository, allUsersName));
     159             :     }
     160             : 
     161         138 :     return AccountState.fromAccountConfig(externalIds, cfg, defaultPreferences);
     162             :   }
     163             : 
     164             :   public static Stream<Account.Id> readUserRefs(Repository repo) throws IOException {
     165          35 :     return repo.getRefDatabase().getRefsByPrefix(RefNames.REFS_USERS).stream()
     166          35 :         .map(r -> Account.Id.fromRef(r.getName()))
     167          35 :         .filter(Objects::nonNull);
     168             :   }
     169             : }

Generated by: LCOV version 1.16+git.20220603.dfeb750