This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

core / appview / repo / index.go
10 kB 396 lines
1package repo 2 3import ( 4 "errors" 5 "fmt" 6 "maps" 7 "net/http" 8 "net/url" 9 "slices" 10 "sort" 11 "strings" 12 "sync" 13 "time" 14 15 "context" 16 "encoding/json" 17 18 "github.com/bluesky-social/indigo/atproto/syntax" 19 "github.com/go-git/go-git/v5/plumbing" 20 "tangled.org/core/api/tangled" 21 "tangled.org/core/appview/commitverify" 22 "tangled.org/core/appview/db" 23 "tangled.org/core/appview/models" 24 "tangled.org/core/appview/pages" 25 "tangled.org/core/appview/pages/markup" 26 "tangled.org/core/appview/pipelines" 27 "tangled.org/core/types" 28 29 "github.com/go-chi/chi/v5" 30 "github.com/go-enry/go-enry/v2" 31 "github.com/samber/lo" 32) 33 34func (rp *Repo) Index(w http.ResponseWriter, r *http.Request) { 35 l := rp.logger.With("handler", "RepoIndex") 36 37 ref := chi.URLParam(r, "ref") 38 ref, _ = url.PathUnescape(ref) 39 40 f, err := rp.repoResolver.Resolve(r) 41 if err != nil { 42 l.Error("failed to fully resolve repo", "err", err) 43 return 44 } 45 46 user := rp.oauth.GetMultiAccountUser(r) 47 48 if user != nil { 49 userDid := user.Did 50 repoDid := f.RepoDid 51 go func() { 52 if err := db.UpsertRecentLink(rp.db, userDid, models.RecentLinkTypeRepo, repoDid); err != nil { 53 l.Error("failed to upsert recent link", "err", err) 54 } 55 }() 56 } 57 58 // Build index response from multiple XRPC calls 59 result, err := rp.buildIndexResponse(r.Context(), f, ref) 60 if err != nil { 61 l.Error("failed to build index response", "err", err) 62 rp.pages.RepoIndexPage(w, pages.RepoIndexParams{ 63 BaseParams: pages.BaseParamsFromContext(r.Context()), 64 KnotUnreachable: true, 65 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 66 }) 67 return 68 } 69 70 tagMap := make(map[string][]string) 71 for _, tag := range result.Tags { 72 hash := tag.Hash 73 if tag.Tag != nil { 74 hash = tag.Tag.Target.String() 75 } 76 tagMap[hash] = append(tagMap[hash], tag.Name) 77 } 78 79 for _, branch := range result.Branches { 80 hash := branch.Hash 81 tagMap[hash] = append(tagMap[hash], branch.Name) 82 } 83 84 sortFiles(result.Files) 85 86 slices.SortFunc(result.Branches, func(a, b types.Branch) int { 87 if a.Name == result.Ref { 88 return -1 89 } 90 if a.IsDefault { 91 return -1 92 } 93 if b.IsDefault { 94 return 1 95 } 96 if a.Commit != nil && b.Commit != nil { 97 if a.Commit.Committer.When.Before(b.Commit.Committer.When) { 98 return 1 99 } else { 100 return -1 101 } 102 } 103 return strings.Compare(a.Name, b.Name) * -1 104 }) 105 106 commitCount := len(result.Commits) 107 branchCount := len(result.Branches) 108 tagCount := len(result.Tags) 109 fileCount := len(result.Files) 110 111 commitCount, branchCount, tagCount = balanceIndexItems(commitCount, branchCount, tagCount, fileCount) 112 commitsTrunc := result.Commits[:min(commitCount, len(result.Commits))] 113 tagsTrunc := result.Tags[:min(tagCount, len(result.Tags))] 114 branchesTrunc := result.Branches[:min(branchCount, len(result.Branches))] 115 116 var shas []string 117 for _, c := range commitsTrunc { 118 shas = append(shas, c.Hash.String()) 119 } 120 type pipelineResult struct { 121 pipelines map[string]types.Pipeline 122 err error 123 } 124 pipelineCh := make(chan pipelineResult, 1) 125 go func() { 126 p, err := pipelines.FetchStatuses(r.Context(), f, shas) 127 pipelineCh <- pipelineResult{p, err} 128 }() 129 130 emails := uniqueEmails(commitsTrunc) 131 emailToDidMap, err := db.GetEmailToDid(rp.db, emails, true) 132 if err != nil { 133 l.Error("failed to get email to did map", "err", err) 134 } 135 136 vc, err := commitverify.GetVerifiedCommits(rp.db, emailToDidMap, commitsTrunc) 137 if err != nil { 138 l.Error("failed to GetVerifiedObjectCommits", "err", err) 139 } 140 141 var languageInfo []types.RepoLanguageDetails 142 if !result.IsEmpty { 143 langs, err := rp.getLanguageInfo(r.Context(), syntax.DID(f.RepoDid), result.Ref) 144 if err != nil { 145 l.Warn("failed to compute language percentages", "err", err) 146 // non-fatal 147 } else if ref == "" { // when request didn't specified ref, we are fetching default branch. 148 if err := func(repo syntax.DID, ref string, langs []*tangled.GitTempListLanguages_Language) error { 149 current := lo.SliceToMap(langs, func(lang *tangled.GitTempListLanguages_Language) (string, int64) { 150 return lang.Name, lang.Size 151 }) 152 153 existing, err := db.GetRepoLanguages(rp.db, repo, ref) 154 if err != nil { 155 return err 156 } 157 if maps.Equal(current, existing) { 158 return nil 159 } 160 161 tx, err := rp.db.Begin() 162 if err != nil { 163 return err 164 } 165 defer tx.Rollback() 166 167 mlangs := lo.Map(langs, func(lang *tangled.GitTempListLanguages_Language, _ int) models.RepoLanguage { 168 return models.RepoLanguage{ 169 RepoDid: repo, 170 Ref: ref, 171 IsDefaultRef: true, 172 Language: lang.Name, 173 Bytes: lang.Size, 174 } 175 }) 176 177 if err := db.UpdateRepoLanguages(tx, repo, ref, mlangs); err != nil { 178 return err 179 } 180 181 return tx.Commit() 182 }(syntax.DID(f.RepoDid), result.Ref, langs); err != nil { 183 l.Error("failed to populate appview repo languages index", "err", err) 184 // non-fatal 185 } 186 languageInfo = makeLanguageStats(langs) 187 } 188 } 189 190 rp.pages.RepoIndexPage(w, pages.RepoIndexParams{ 191 BaseParams: pages.BaseParamsFromContext(r.Context()), 192 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 193 TagMap: tagMap, 194 RepoIndexResponse: *result, 195 CommitsTrunc: commitsTrunc, 196 TagsTrunc: tagsTrunc, 197 // ForkInfo: forkInfo, // TODO: reinstate this after xrpc properly lands 198 BranchesTrunc: branchesTrunc, 199 EmailToDid: emailToDidMap, 200 VerifiedCommits: vc, 201 Languages: languageInfo, 202 }) 203} 204 205func (rp *Repo) getLanguageInfo( 206 ctx context.Context, 207 repoId syntax.DID, 208 ref string, 209) ([]*tangled.GitTempListLanguages_Language, error) { 210 // non-fatal, fetch langs from knotmirror via XRPC 211 xrpcc := rp.knotMirrorXRPCClient() 212 out, err := tangled.GitTempListLanguages(ctx, xrpcc, ref, repoId.String()) 213 if err != nil { 214 return nil, fmt.Errorf("calling knotmirror git.listLanguages: %w", err) 215 } 216 217 if out == nil || out.Languages == nil { 218 return nil, nil 219 } 220 221 return out.Languages, nil 222} 223 224func makeLanguageStats(langs []*tangled.GitTempListLanguages_Language) []types.RepoLanguageDetails { 225 if len(langs) == 0 { 226 return nil 227 } 228 var total int64 229 for _, lang := range langs { 230 total += lang.Size 231 } 232 233 var languageStats []types.RepoLanguageDetails 234 for _, l := range langs { 235 languageStats = append(languageStats, types.RepoLanguageDetails{ 236 Name: l.Name, 237 Color: enry.GetColor(l.Name), 238 Percentage: float32(l.Size) / float32(total) * 100, 239 }) 240 } 241 242 sort.Slice(languageStats, func(i, j int) bool { 243 if languageStats[i].Name == enry.OtherLanguage { 244 return false 245 } 246 if languageStats[j].Name == enry.OtherLanguage { 247 return true 248 } 249 if languageStats[i].Percentage != languageStats[j].Percentage { 250 return languageStats[i].Percentage > languageStats[j].Percentage 251 } 252 return languageStats[i].Name < languageStats[j].Name 253 }) 254 return languageStats 255} 256 257// buildIndexResponse creates a RepoIndexResponse by combining multiple xrpc calls in parallel 258func (rp *Repo) buildIndexResponse(ctx context.Context, repo *models.Repo, ref string) (*types.RepoIndexResponse, error) { 259 xrpcc := rp.knotMirrorXRPCClient() 260 261 branchesBytes, err := tangled.GitTempListBranches(ctx, xrpcc, "", 0, repo.RepoDid) 262 if err != nil { 263 return nil, fmt.Errorf("calling knotmirror git.listBranches: %w", err) 264 } 265 266 var branchesResp types.RepoBranchesResponse 267 if err := json.Unmarshal(branchesBytes, &branchesResp); err != nil { 268 return nil, fmt.Errorf("failed to unmarshal branches response: %w", err) 269 } 270 271 // if no ref specified, use default branch or first available 272 if ref == "" { 273 for _, branch := range branchesResp.Branches { 274 if branch.IsDefault { 275 ref = branch.Name 276 break 277 } 278 } 279 } 280 281 // if ref is still empty, this means the default branch is not set 282 if ref == "" { 283 return &types.RepoIndexResponse{ 284 IsEmpty: true, 285 Branches: branchesResp.Branches, 286 TotalBranches: branchesResp.Total, 287 }, nil 288 } 289 290 // now run the remaining queries in parallel 291 var wg sync.WaitGroup 292 var errs error 293 294 var ( 295 tagsResp types.RepoTagsResponse 296 treeResp *tangled.GitTempGetTree_Output 297 logResp types.RepoLogResponse 298 readmeContent string 299 readmeFileName string 300 ) 301 302 // tags 303 wg.Go(func() { 304 tagsBytes, err := tangled.GitTempListTags(ctx, xrpcc, "", 0, repo.RepoDid) 305 if err != nil { 306 errs = errors.Join(errs, fmt.Errorf("failed to call git.ListTags: %w", err)) 307 return 308 } 309 310 if err := json.Unmarshal(tagsBytes, &tagsResp); err != nil { 311 errs = errors.Join(errs, fmt.Errorf("failed to unmarshal git.ListTags: %w", err)) 312 } 313 }) 314 315 // tree/files 316 wg.Go(func() { 317 resp, err := tangled.GitTempGetTree(ctx, xrpcc, "", ref, repo.RepoDid) 318 if err != nil { 319 errs = errors.Join(errs, fmt.Errorf("failed to call git.GetTree: %w", err)) 320 return 321 } 322 treeResp = resp 323 324 for _, file := range resp.Files { 325 if markup.IsReadmeFile(file.Name, file.Mode) { 326 readmeFileName = file.Name 327 break 328 } 329 } 330 331 if readmeFileName != "" { 332 bytes, err := tangled.GitTempGetBlob(ctx, xrpcc, readmeFileName, ref, repo.RepoDid) 333 if err != nil { 334 errs = errors.Join(errs, fmt.Errorf("failed to call git.getBlob: %w", err)) 335 return 336 } 337 readmeContent = string(bytes) 338 } 339 }) 340 341 // commits 342 wg.Go(func() { 343 logBytes, err := tangled.GitTempListCommits(ctx, xrpcc, "", 50, ref, repo.RepoDid) 344 if err != nil { 345 errs = errors.Join(errs, fmt.Errorf("failed to call git.ListCommits: %w", err)) 346 return 347 } 348 349 if err := json.Unmarshal(logBytes, &logResp); err != nil { 350 errs = errors.Join(errs, fmt.Errorf("failed to unmarshal git.ListCommits: %w", err)) 351 } 352 }) 353 354 wg.Wait() 355 356 if errs != nil { 357 return nil, errs 358 } 359 360 var files []types.NiceTree 361 if treeResp != nil && treeResp.Files != nil { 362 for _, file := range treeResp.Files { 363 niceFile := types.NiceTree{ 364 Name: file.Name, 365 Mode: file.Mode, 366 Size: file.Size, 367 } 368 369 if file.Last_commit != nil { 370 when, _ := time.Parse(time.RFC3339, file.Last_commit.When) 371 niceFile.LastCommit = &types.LastCommitInfo{ 372 Hash: plumbing.NewHash(file.Last_commit.Hash), 373 Message: file.Last_commit.Message, 374 When: when, 375 } 376 } 377 files = append(files, niceFile) 378 } 379 } 380 381 result := &types.RepoIndexResponse{ 382 IsEmpty: false, 383 Ref: ref, 384 Readme: readmeContent, 385 ReadmeFileName: readmeFileName, 386 Commits: logResp.Commits, 387 Files: files, 388 Branches: branchesResp.Branches, 389 TotalBranches: branchesResp.Total, 390 Tags: tagsResp.Tags, 391 TotalTags: tagsResp.Total, 392 TotalCommits: logResp.Total, 393 } 394 395 return result, nil 396}