File: quick_start.md

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (614 lines) | stat: -rw-r--r-- 20,858 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
---
stage: Monitor
group: Analytics Instrumentation
info: Any user with at least the Maintainer role can merge updates to this content. For details, see https://docs.gitlab.com/ee/development/development_processes.html#development-guidelines-review.
---

# Quick start for Internal Event Tracking

In an effort to provide a more efficient, scalable, and unified tracking API, GitLab is deprecating existing RedisHLL and Snowplow tracking. Instead, we're implementing a new `track_event` (Backend) and `trackEvent`(Frontend) method.
With this approach, we can update both RedisHLL counters and send Snowplow events without worrying about the underlying implementation.

In order to instrument your code with Internal Events Tracking you need to do three things:

1. Define an event
1. Define one or more metrics
1. Trigger the event

## Defining event and metrics

To create event and/or metric definitions, use the `internal_events` generator from the `gitlab` directory:

```shell
scripts/internal_events/cli.rb
```

This CLI will help you create the correct definition files based on your specific use-case, then provide code examples for instrumentation and testing.

Events should be named in the format of `<action>_<target_of_action>_<where/when>`, valid examples are `create_ci_build` or `click_previous_blame_on_blob_page`.

## Trigger events

Triggering an event and thereby updating a metric is slightly different on backend and frontend. Refer to the relevant section below.

### Backend tracking

<div class="video-fallback">
  Watch the video about <a href="https://www.youtube.com/watch?v=Teid7o_2Mmg">Backend instrumentation using Internal Events</a>
</div>
<figure class="video-container">
  <iframe src="https://www.youtube-nocookie.com/embed/Teid7o_2Mmg" frameborder="0" allowfullscreen> </iframe>
</figure>

To trigger an event, call the `track_internal_event` method from the `Gitlab::InternalEventsTracking` module with the desired arguments:

```ruby
include Gitlab::InternalEventsTracking

track_internal_event(
  "create_ci_build",
  user: user,
  namespace: namespace,
  project: project
)
```

This method automatically increments all RedisHLL metrics relating to the event `create_ci_build`, and sends a corresponding Snowplow event with all named arguments and standard context (SaaS only).
In addition, the name of the class triggering the event is saved in the `category` property of the Snowplow event.

If you have defined a metric with a `unique` property such as `unique: project.id` it is required that you provide the `project` argument.

It is encouraged to fill out as many of `user`, `namespace` and `project` as possible as it increases the data quality and make it easier to define metrics in the future.

If a `project` but no `namespace` is provided, the `project.namespace` is used as the `namespace` for the event.

In some cases you might want to specify the `category` manually or provide none at all. To do that, you can call the `InternalEvents.track_event` method directly instead of using the module.

In case when a feature is enabled through multiple namespaces and its required to track why the feature is enabled, it is
possible to pass an optional `feature_enabled_by_namespace_ids` parameter with an array of namespace ids.

```ruby
track_internal_event(
  ...
  feature_enabled_by_namespace_ids: [namespace_one.id, namespace_two.id]
)
```

#### Additional properties

Additional properties can be passed when tracking events. They can be used to save additional data related to given event.

Tracking classes already have three built-in properties:

- `label` (string)
- `property` (string)
- `value`(numeric)

The arbitrary naming and typing of the these three properties is due to constraints from the data extraction process.
It's recommended to use these properties first, even if their name does not match with the data you want to track. You can further describe what is the actual data being tracked by using the `description` property in the YAML definition of the event. For an example, see
[`create_ci_internal_pipeline.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/537ea367dab731e886e6040d8399c430fdb67ab7/config/events/create_ci_internal_pipeline.yml):

```ruby
additional_properties:
  label:
    description: The source of the pipeline, e.g. a push, a schedule or similar.
  property:
    description: The source of the config, e.g. the repository, auto_devops or similar.
```

Additional properties are passed by including the `additional_properties` hash in the `#track_event` call:

```ruby
track_internal_event(
  "create_ci_build",
  user: user,
  additional_properties: {
    label: source, # The label is tracking the source of the pipeline
    property: config_source # The property is tracking the source of the configuration
  }
)
```

If you need to pass more than the three built-in additional properties, you can use the `additional_properties` hash with your custom keys:

```ruby
track_internal_event(
  "code_suggestion_accepted",
  user: user,
  additional_properties: {
    # Built-in properties
    label: editor_name,
    property: suggestion_type,
    value: suggestion_shown_duration,
    # Your custom properties
    lang: 'ruby',
    custom_key: 'custom_value'
  }
)
```

Please add custom properties only in addition to the built-in properties. Additional properties can only have string or numeric values.

#### Controller and API helpers

There is a helper module `ProductAnalyticsTracking` for controllers you can use to track internal events for particular controller actions by calling `#track_internal_event`:

```ruby
class Projects::PipelinesController < Projects::ApplicationController
  include ProductAnalyticsTracking

  track_internal_event :charts, name: 'visit_charts_on_ci_cd_pipelines', conditions: -> { should_track_ci_cd_pipelines? }

  def charts
    ...
  end

  private

  def should_track_ci_cd_pipelines?
    params[:chart].blank? || params[:chart] == 'pipelines'
  end
end
```

You need to add these two methods to the controller body, so that the helper can get the current project and namespace for the event:

```ruby
  private

  def tracking_namespace_source
    project.namespace
  end

  def tracking_project_source
    project
  end
```

Also, there is an API helper:

```ruby
track_event(
  event_name,
  user: current_user,
  namespace_id: namespace_id,
  project_id: project_id
)
```

### Backend testing

When testing code that simply triggers an internal event and make sure it increments all the related metrics,
you can use the `internal_event_tracking` shared example.

```ruby
it_behaves_like 'internal event tracking' do
  let(:event) { 'update_issue_severity' }
  let(:project) { issue.project }
  let(:user) { issue.author }
  let(:additional_properties) { { label: issue.issueable_severity } }
  subject(:service_action) { described_class.new(issue).execute }
end
```

It requires a context containing:

- `subject` - the action that triggers the event
- `event` - the name of the event

Optionally, the context can contain:

- `user`
- `project`
- `namespace`. If not provided, `project.namespace` will be used (if `project` is available).
- `category`
- `additional_properties`
- `event_attribute_overrides` - is used when its necessary to override the attributes available in parent context. For example:

```ruby
let(:event) { 'create_new_issue' }

it_behaves_like 'internal event tracking' do
  let(:event_attribute_overrides) { { event: 'create_new_milestone'} }

  subject(:service_action) { described_class.new(issue).save }
end
```

These legacy options are now deprecated:

- `label`
- `property`
- `value`

Prefer using `additional_properties` instead.

#### Composable matchers

When a singe action triggers an event multiple times, triggers multiple different events, or increments some metrics but not others for the event,
you can use the `trigger_internal_events` and `increment_usage_metrics` matchers.

```ruby
 expect { subject }
  .to trigger_internal_events('web_ide_viewed')
  .with(user: user, project: project, namespace: namespace)
  .and increment_usage_metrics('counts.web_views')
```

The `trigger_internal_events` matcher accepts the same chain methods as the [`receive`](https://rubydoc.info/github/rspec/rspec-mocks/RSpec/Mocks/ExampleMethods#receive-instance_method) matcher (`#once`, `#at_most`, etc). By default, it expects the provided events to be triggered only once.

The chain method `#with` accepts following parameters:

- `user` - User object
- `project` - Project object
- `namespace` - Namespace object. If not provided, it will be set to `project.namespace`
- `additional_properties` - Hash. Additional properties to be sent with the event. For example: `{ label: 'scheduled', value: 20 }`
- `category` - String. If not provided, it will be set to the class name of the object that triggers the event

The `increment_usage_metrics` matcher accepts the same chain methods as the [`change`](https://rubydoc.info/gems/rspec-expectations/RSpec%2FMatchers:change) matcher (`#by`, `#from`, `#to`, etc). By default, it expects the provided metrics to be incremented by one.

```ruby
expect { subject }
  .to trigger_internal_events('web_ide_viewed')
  .with(user: user, project: project, namespace: namespace)
  .exactly(3).times
```

Both matchers are composable with other matchers that act on a block (like `change` matcher).

```ruby
expect { subject }
  .to trigger_internal_events('mr_created')
    .with(user: user, project: project, category: category, additional_properties: { label: label } )
  .and increment_usage_metrics('counts.deployments')
    .at_least(:once)
  .and change { mr.notes.count }.by(1)
```

To test that an event was not triggered, you can use the `not_trigger_internal_events` matcher. It does not accept message chains.

```ruby
expect { subject }.to trigger_internal_events('mr_created')
    .with(user: user, project: project, namespace: namespace)
  .and increment_usage_metrics('counts.deployments')
  .and not_trigger_internal_events('pipeline_started')
```

Or you can use the `not_to` syntax:

```ruby
expect { subject }.not_to trigger_internal_events('mr_created', 'member_role_created')
```

### Frontend tracking

Any frontend tracking call automatically passes the values `user.id`, `namespace.id`, and `project.id` from the current context of the page.

If you need to pass any further properties, such as `extra`, `context`, `label`, `property`, and `value`, you can use the [deprecated snowplow implementation](https://archives.docs.gitlab.com/16.4/ee/development/internal_analytics/snowplow/implementation.html). In this case, let us know about your specific use-case in our [feedback issue for Internal Events](https://gitlab.com/gitlab-org/analytics-section/analytics-instrumentation/internal/-/issues/690).

#### Vue components

In Vue components, tracking can be done with [Vue mixin](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/tracking/internal_events.js#L29).

To implement Vue component tracking:

1. Import the `InternalEvents` library and call the `mixin` method:

     ```javascript
     import { InternalEvents } from '~/tracking';
     const trackingMixin = InternalEvents.mixin();
    ```

1. Use the mixin in the component:

   ```javascript
   export default {
     mixins: [trackingMixin],

     data() {
       return {
         expanded: false,
       };
     },
   };
   ```

1. Call the `trackEvent` method. Tracking options can be passed as the second parameter:

   ```javascript
   this.trackEvent('click_previous_blame_on_blob_page');
   ```

   Or use the `trackEvent` method in the template:

   ```html
   <template>
     <div>
       <button data-testid="toggle" @click="toggle">Toggle</button>

       <div v-if="expanded">
         <p>Hello world!</p>
         <button @click="trackEvent('click_previous_blame_on_blob_page')">Track another event</button>
       </div>
     </div>
   </template>
   ```

#### Raw JavaScript

For tracking events directly from arbitrary frontend JavaScript code, a module for raw JavaScript is provided. This can be used outside of a component context where the Mixin cannot be utilized.

```javascript
import { InternalEvents } from '~/tracking';
InternalEvents.trackEvent('click_previous_blame_on_blob_page');
```

#### Data-event attribute

This attribute ensures that if we want to track GitLab internal events for a button, we do not need to write JavaScript code on Click handler. Instead, we can just add a data-event-tracking attribute with event value and it should work. This can also be used with HAML views.

```html
  <gl-button
    data-event-tracking="click_previous_blame_on_blob_page"
  >
   Click Me
  </gl-button>
```

#### Haml

```haml
= render Pajamas::ButtonComponent.new(button_options: { class: 'js-settings-toggle',  data: { event_tracking: 'click_previous_blame_on_blob_page' }}) do
```

#### Internal events on render

Sometimes we want to send internal events when the component is rendered or loaded. In these cases, we can add the `data-event-tracking-load="true"` attribute:

```haml
= render Pajamas::ButtonComponent.new(button_options: { data: { event_tracking_load: 'true', event_tracking: 'click_previous_blame_on_blob_page' } }) do
        = _("New project")
```

#### Additional properties

You can include additional properties with events to save additional data. When included you must define each additional property in the `additional_properties` field. It is possible to send the three built-in additional properties with keys `label` (string), `property` (string) and `value`(numeric) and [custom additional properties](quick_start.md#additional-properties) if the built-in properties are not sufficient.

NOTE:
Do not pass the page URL or page path as an additional property because we already track the pseudonymized page URL for each event.
Getting the URL from `window.location` does not pseudonymize project and namespace information [as documented](https://metrics.gitlab.com/identifiers).

For Vue Mixin:

```javascript
   this.trackEvent('click_view_runners_button', {
    label: 'group_runner_form',
    property: dynamicPropertyVar,
    value: 20
   });
```

For raw JavaScript:

```javascript
   InternalEvents.trackEvent('click_view_runners_button', {
    label: 'group_runner_form',
    property: dynamicPropertyVar,
    value: 20
   });
```

For data-event attributes:

```javascript
  <gl-button
    data-event-tracking="click_view_runners_button"
    data-event-label="group_runner_form"
    :data-event-property=dynamicPropertyVar
    data-event-additional='{"key1": "value1", "key2": "value2"}'
  >
   Click Me
  </gl-button>
```

For Haml:

```haml
= render Pajamas::ButtonComponent.new(button_options: { class: 'js-settings-toggle',  data: { event_tracking: 'action', event_label: 'group_runner_form', event_property: dynamic_property_var, event_value: 2, event_additional: '{"key1": "value1", "key2": "value2"}' }}) do
```

#### Frontend testing

##### JavaScript/Vue

If you are using the `trackEvent` method in any of your code, whether it is in raw JavaScript or a Vue component, you can use the `useMockInternalEventsTracking` helper method to assert if `trackEvent` is called.

For example, if we need to test the below Vue component,

```vue
<script>
import { GlButton } from '@gitlab/ui';
import { InternalEvents } from '~/tracking';
import { __ } from '~/locale';

export default {
  components: {
    GlButton,
  },
  mixins: [InternalEvents.mixin()],
  methods: {
    handleButtonClick() {
      // some application logic
      // when some event happens fire tracking call
      this.trackEvent('click_view_runners_button', {
        label: 'group_runner_form',
        property: 'property_value',
        value: 3,
      });
    },
  },
  i18n: {
    button1: __('Sample Button'),
  },
};
</script>
<template>
  <div style="display: flex; height: 90vh; align-items: center; justify-content: center">
    <gl-button class="sample-button" @click="handleButtonClick">
      {{ $options.i18n.button1 }}
    </gl-button>
  </div>
</template>
```

Below would be the test case for above component.

```javascript
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
import DeleteApplication from '~/admin/applications/components/delete_application.vue';
import { useMockInternalEventsTracking } from 'helpers/tracking_internal_events_helper';

describe('DeleteApplication', () => {
  /** @type {import('helpers/vue_test_utils_helper').ExtendedWrapper} */
  let wrapper;

  const createComponent = () => {
    wrapper = shallowMountExtended(DeleteApplication);
  };

  beforeEach(() => {
    createComponent();
  });

  describe('sample button 1', () => {
    const { bindInternalEventDocument } = useMockInternalEventsTracking();
    it('should call trackEvent method when clicked on sample button', async () => {
      const { trackEventSpy } = bindInternalEventDocument(wrapper.element);

      await wrapper.find('.sample-button').vm.$emit('click');

      expect(trackEventSpy).toHaveBeenCalledWith(
        'click_view_runners_button',
        {
          label: 'group_runner_form',
          property: 'property_value',
          value: 3,
        },
        undefined,
      );
    });
  });
});
```

If you are using tracking attributes for in Vue/View templates like below,

```vue
<script>
import { GlButton } from '@gitlab/ui';
import { InternalEvents } from '~/tracking';
import { __ } from '~/locale';

export default {
  components: {
    GlButton,
  },
  mixins: [InternalEvents.mixin()],
  i18n: {
    button1: __('Sample Button'),
  },
};
</script>
<template>
  <div style="display: flex; height: 90vh; align-items: center; justify-content: center">
    <gl-button
      class="sample-button"
      data-event-tracking="click_view_runners_button"
      data-event-label="group_runner_form"
    >
      {{ $options.i18n.button1 }}
    </gl-button>
  </div>
</template>
```

Below would be the test case for above component.

```javascript
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
import DeleteApplication from '~/admin/applications/components/delete_application.vue';
import { useMockInternalEventsTracking } from 'helpers/tracking_internal_events_helper';

describe('DeleteApplication', () => {
  /** @type {import('helpers/vue_test_utils_helper').ExtendedWrapper} */
  let wrapper;

  const createComponent = () => {
    wrapper = shallowMountExtended(DeleteApplication);
  };

  beforeEach(() => {
    createComponent();
  });

  describe('sample button', () => {
    const { bindInternalEventDocument } = useMockInternalEventsTracking();
    it('should call trackEvent method when clicked on sample button', () => {
      const { triggerEvent, trackEventSpy } = bindInternalEventDocument(wrapper.element);
      triggerEvent('.sample-button');
      expect(trackEventSpy).toHaveBeenCalledWith('click_view_runners_button', {
        label: 'group_runner_form',
      });
    });
  });
});
```

#### Haml with data attributes

If you are using the data attributes to register tracking at the Haml layer,
you can use the `have_internal_tracking` matcher method to assert if expected data attributes are assigned.

For example, if we need to test the below Haml,

```haml
%div{ data: { testid: '_testid_', event_tracking: 'render', event_label: '_tracking_label_' } }
```

Below would be the test case for above haml.

- [RSpec view specs](https://rspec.info/features/6-0/rspec-rails/view-specs/view-spec/)

```ruby
  it 'assigns the tracking items' do
    render

    expect(rendered).to have_internal_tracking(event: 'render', label: '_tracking_label_', testid: '_testid_')
  end
```

- [ViewComponent](https://viewcomponent.org/) specs

```ruby
  it 'assigns the tracking items' do
    render_inline(component)

    expect(page).to have_internal_tracking(event: 'render', label: '_tracking_label_', testid: '_testid_')
  end
```

`event` is required for the matcher and `label`/`testid` are optional.
It is recommended to use `testid` when possible for exactness.
When you want to ensure that tracking isn't assigned, you can use `not_to` with the above matchers.

### Using Internal Events API

You can also use our API to track events from other systems connected to a GitLab instance.
See the [Usage Data API documentation](../../../api/usage_data.md#events-tracking-api) for more information.

### Internal Events on other systems

Apart from the GitLab codebase, we are using Internal Events for the systems listed below.

1. [AI Gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/-/blob/main/docs/internal_events.md?ref_type=heads)
1. [Switchboard](https://gitlab.com/gitlab-com/gl-infra/gitlab-dedicated/switchboard/-/blob/main/docs/internal_events.md)