Chmouel Boudjnah
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    **Overall Change:** The core change introduces a new metric: `pipelines_as_code_git_provider_api_request_count`. This metric aims to count the number of API requests made by Pipelines-as-Code (PaC) to the underlying Git providers (GitHub, GitLab, Bitbucket, etc.). This involves: 1. Defining the metric and its view in `pkg/metrics/metrics.go`. 2. Adding a method `ReportGitProviderAPIUsage` to the `Recorder` to increment the metric. 3. Modifying each Git provider implementation (`pkg/provider/*`) to: * Store necessary information (repository, event type). * Initialize a metrics recorder instance (lazily). * Call a new helper method (`recordAPIUsageMetrics`) whenever the provider's API client is accessed (`Client()` or `ScmClient()`). * The helper method calls `ReportGitProviderAPIUsage`. 4. Updating documentation (`docs/content/docs/install/metrics.md`) to include the new metric. 5. Updating tests (`pkg/provider/github/github_test.go`, `pkg/reconciler/emit_metrics_test.go`) to account for the new metric. **Analysis Results:** **Bugs:** 1. **Critical Bug: Incorrect Receiver Type for Client Accessors:** * **Files:** * `pkg/provider/bitbucketcloud/bitbucket.go` * `pkg/provider/bitbucketdatacenter/bitbucketdatacenter.go` * `pkg/provider/gitea/gitea.go` * `pkg/provider/gitlab/gitlab.go` * **Issue:** The methods `Client()` (and `ScmClient()` for Bitbucket DC) in these files have *value receivers* (e.g., `func (v Provider) Client() ...`). However, the `recordAPIUsageMetrics` method called within them attempts to lazily initialize the `v.metrics` field (`if v.metrics == nil { ...; v.metrics = m }`). Because the receiver is a value (a copy), any modification to `v.metrics` inside `recordAPIUsageMetrics` will *not* persist on the original `Provider` struct instance after the `Client()` method returns. * **Consequence:** The `v.metrics` field will likely remain `nil` for these providers. Subsequent calls to `Client()` will repeatedly attempt (and fail to persist) initialization, and the actual `v.metrics.ReportGitProviderAPIUsage` call will likely operate on a `nil` recorder or fail the `assertInitialized` check within `ReportGitProviderAPIUsage`, meaning the metric will not be recorded correctly for these providers. * **Fix:** Change the receiver type for `Client()` (and `ScmClient()` where applicable) in these files from `Provider` to `*Provider`. * Example (GitLab): Change `func (v Provider) Client() *gitlab.Client` to `func (v *Provider) Client() *gitlab.Client`. * **Note:** The GitHub provider (`pkg/provider/github/github.go`) *correctly* updated its `Client` method to use a pointer receiver (`func (v *Provider) Client() *github.Client`). This inconsistency highlights the bug in the other providers. 2. **Potential Bug/Semantic Mismatch: Metric Granularity:** * **Files:** All `pkg/provider/*` files. * **Issue:** The metric is incremented *every time the `Client()` or `ScmClient()` accessor method is called*. This counts accesses to the *Go client object*, not necessarily actual outgoing HTTP API requests made by that client to the Git provider's backend. A single logical operation within PaC might call `Client()` multiple times, or a complex operation within the underlying Git client library might make several HTTP requests after only one `Client()` call. Conversely, `Client()` might be called but no actual API request made in that specific path. * **Consequence:** The metric count might not accurately reflect the true number of HTTP API calls sent to the Git provider. It counts the *intent* or *opportunity* to make a call more than the call itself. This could lead to significant over or undercounting depending on internal PaC logic and the behavior of the specific Git client libraries. The name `...api_request_count` implies actual requests. * **Fix (More Complex):** A more accurate approach would involve instrumenting the `http.Client` used by the underlying Git provider libraries (e.g., using an `http.RoundTripper` wrapper) to count actual outgoing HTTP requests. However, the current approach might be considered "good enough" as a proxy, but its limitation should be understood. **Spelling Mistakes:** * No obvious spelling mistakes were found in the code or documentation changes. **Idiomatic Improvements / Code Style:** 1. **Metrics Initialization:** * **Files:** All `pkg/provider/*` files (`recordAPIUsageMetrics` method). * **Issue:** Each provider instance lazily initializes its *own* `v.metrics` pointer by calling the global `metrics.NewRecorder()`. While `NewRecorder` uses `sync.Once` to protect the *global* state, having each provider instance potentially call it feels slightly indirect. * **Suggestion:** A more idiomatic approach might be to pass the initialized global recorder (`metrics.R`) to the provider when it's set up, for example, within the `SetClient` method or potentially via a constructor pattern if applicable. This avoids the lazy initialization logic within the `recordAPIUsageMetrics` helper. * Example (in `SetClient`): `v.metrics = metrics.R` (assuming `metrics.R` is the initialized global recorder). Then `recordAPIUsageMetrics` wouldn't need the `if v.metrics == nil` block. 2. **Error Handling in `NewRecorder`:** * **File:** `pkg/metrics/metrics.go` * **Issue:** The pattern `if errRegistering != nil { ErrRegistering = errRegistering; return }` is repeated many times inside the `sync.Once.Do`. * **Suggestion (Minor):** While functional, it could be slightly cleaner to check the error immediately after each `tag.NewKey` or `view.Register` call and return early if an error occurs. The `ErrRegistering` variable would still capture the first error encountered. This is a minor stylistic point. 3. **Error Logging in `recordAPIUsageMetrics`:** * **Files:** All `pkg/provider/*` files. * **Issue:** Errors during metric initialization (`metrics.NewRecorder()`) or reporting (`v.metrics.ReportGitProviderAPIUsage()`) are logged but not returned or propagated. * **Suggestion:** This is generally acceptable for metrics (don't block primary functionality), but it's worth noting that failures will only be visible in logs. Ensure logging levels and monitoring are adequate. **Documentation:** * The documentation update in `docs/content/docs/install/metrics.md` is clear and accurately describes the new metric. * The PromQL examples are helpful, especially the note about summing metrics from the controller and watcher. **Testing:** * The tests added in `pkg/provider/github/github_test.go` are good. They correctly use `metricstest` helpers and verify the metric count for different scenarios *based on the current implementation* (i.e., counting `Client()` calls). * Adding similar metric count tests for the other providers would be valuable once **Bug 1** (Incorrect Receiver Type) is fixed. * The `resetMetrics` helper and updates to `unregisterMetrics` are necessary and correctly implemented for test isolation. **Summary:** The change successfully introduces the infrastructure for the new metric. However, **Bug 1 (Incorrect Receiver Type)** is critical and prevents the metric from working correctly for most providers. **Bug 2 (Metric Granularity)** represents a potential semantic mismatch between what the metric name implies and what is actually counted, which might lead to inaccurate data. The suggested idiomatic improvements are minor compared to the bugs. The documentation and testing updates (for GitHub) are well done. **Recommendation:** 1. **Fix Bug 1 (Critical):** Change the `Client()` / `ScmClient()` methods in Bitbucket Cloud, Bitbucket Datacenter, Gitea, and GitLab providers to use pointer receivers (`*Provider`). 2. **Evaluate Bug 2:** Discuss whether counting `Client()` calls is sufficient or if instrumenting the HTTP client is necessary for the desired accuracy. Document the chosen approach and its limitations clearly if the current method is kept. 3. **Consider Improvement 1:** Refactor metric initialization to pass the recorder during setup rather than using lazy initialization in each provider. 4. Add metric tests for other providers after Bug 1 is fixed.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully