-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.go
More file actions
4226 lines (3866 loc) · 175 KB
/
Copy pathmonitor.go
File metadata and controls
4226 lines (3866 loc) · 175 KB
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
package contextdev
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"time"
"github.com/context-dot-dev/context-go-sdk/v2/internal/apijson"
"github.com/context-dot-dev/context-go-sdk/v2/internal/apiquery"
"github.com/context-dot-dev/context-go-sdk/v2/internal/requestconfig"
"github.com/context-dot-dev/context-go-sdk/v2/option"
"github.com/context-dot-dev/context-go-sdk/v2/packages/param"
"github.com/context-dot-dev/context-go-sdk/v2/packages/respjson"
"github.com/context-dot-dev/context-go-sdk/v2/shared/constant"
)
// Monitor pages, sitemaps, and extracted website data for exact or semantic
// changes. Webhook payloads are documented by the
// MonitorsChangeDetectedWebhookPayload and MonitorsRunCompletedWebhookPayload
// schemas.
//
// MonitorService contains methods and other services that help with interacting
// with the context.dev API.
//
// Note, unlike clients, this service does not read variables from the environment
// automatically. You should not instantiate this service directly, and instead use
// the [NewMonitorService] method instead.
type MonitorService struct {
options []option.RequestOption
}
// NewMonitorService generates a new service that applies the given options to each
// request. These options are applied after the parent client's options (if there
// is one), and before any request-specific options.
func NewMonitorService(opts ...option.RequestOption) (r MonitorService) {
r = MonitorService{}
r.options = opts
return
}
// Creates a monitor. The request body is a union of the supported target/change
// detection combinations. The monitor runs immediately after creation to create
// its initial baseline.
func (r *MonitorService) New(ctx context.Context, body MonitorNewParams, opts ...option.RequestOption) (res *MonitorNewResponse, err error) {
opts = slices.Concat(r.options, opts)
path := "monitors"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Get a monitor
func (r *MonitorService) Get(ctx context.Context, monitorID string, opts ...option.RequestOption) (res *MonitorGetResponse, err error) {
opts = slices.Concat(r.options, opts)
if monitorID == "" {
err = errors.New("missing required monitor_id parameter")
return nil, err
}
path := fmt.Sprintf("monitors/%s", url.PathEscape(monitorID))
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// Updates a monitor. If `target` or `change_detection` changes, the monitor
// creates a new baseline. Unsupported target/change detection combinations are
// rejected.
func (r *MonitorService) Update(ctx context.Context, monitorID string, body MonitorUpdateParams, opts ...option.RequestOption) (res *MonitorUpdateResponse, err error) {
opts = slices.Concat(r.options, opts)
if monitorID == "" {
err = errors.New("missing required monitor_id parameter")
return nil, err
}
path := fmt.Sprintf("monitors/%s", url.PathEscape(monitorID))
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPatch, path, body, &res, opts...)
return res, err
}
// Lists monitors for the authenticated organization. Supports free-text search
// (`q` over `search_by` fields, `prefix` or `exact` via `search_type`) plus
// status/type/tag filters. Results are paginated via the opaque `cursor`.
func (r *MonitorService) List(ctx context.Context, query MonitorListParams, opts ...option.RequestOption) (res *MonitorListResponse, err error) {
opts = slices.Concat(r.options, opts)
path := "monitors"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Delete a monitor
func (r *MonitorService) Delete(ctx context.Context, monitorID string, opts ...option.RequestOption) (res *MonitorDeleteResponse, err error) {
opts = slices.Concat(r.options, opts)
if monitorID == "" {
err = errors.New("missing required monitor_id parameter")
return nil, err
}
path := fmt.Sprintf("monitors/%s", url.PathEscape(monitorID))
err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
return res, err
}
// Returns credits charged per monitor over an optional [since, until] window,
// newest spenders first.
func (r *MonitorService) GetCreditUsage(ctx context.Context, query MonitorGetCreditUsageParams, opts ...option.RequestOption) (res *MonitorGetCreditUsageResponse, err error) {
opts = slices.Concat(r.options, opts)
path := "monitors/credit-usage"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Returns how many monitors the account has and the maximum it allows.
func (r *MonitorService) GetLimits(ctx context.Context, opts ...option.RequestOption) (res *MonitorGetLimitsResponse, err error) {
opts = slices.Concat(r.options, opts)
path := "monitors/limits"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// Returns an account-wide feed of detected changes across monitors.
func (r *MonitorService) ListAccountChanges(ctx context.Context, query MonitorListAccountChangesParams, opts ...option.RequestOption) (res *MonitorListAccountChangesResponse, err error) {
opts = slices.Concat(r.options, opts)
path := "monitors/changes"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Returns an account-wide feed of monitor runs across all monitors.
func (r *MonitorService) ListAccountRuns(ctx context.Context, query MonitorListAccountRunsParams, opts ...option.RequestOption) (res *MonitorListAccountRunsResponse, err error) {
opts = slices.Concat(r.options, opts)
path := "monitors/runs"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// List changes for a monitor
func (r *MonitorService) ListChanges(ctx context.Context, monitorID string, query MonitorListChangesParams, opts ...option.RequestOption) (res *MonitorListChangesResponse, err error) {
opts = slices.Concat(r.options, opts)
if monitorID == "" {
err = errors.New("missing required monitor_id parameter")
return nil, err
}
path := fmt.Sprintf("monitors/%s/changes", url.PathEscape(monitorID))
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// List monitor runs
func (r *MonitorService) ListRuns(ctx context.Context, monitorID string, query MonitorListRunsParams, opts ...option.RequestOption) (res *MonitorListRunsResponse, err error) {
opts = slices.Concat(r.options, opts)
if monitorID == "" {
err = errors.New("missing required monitor_id parameter")
return nil, err
}
path := fmt.Sprintf("monitors/%s/runs", url.PathEscape(monitorID))
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Get a change
func (r *MonitorService) GetChange(ctx context.Context, changeID string, opts ...option.RequestOption) (res *MonitorGetChangeResponse, err error) {
opts = slices.Concat(r.options, opts)
if changeID == "" {
err = errors.New("missing required change_id parameter")
return nil, err
}
path := fmt.Sprintf("monitors/changes/%s", url.PathEscape(changeID))
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// Triggers an immediate run of the monitor outside its normal schedule. The run is
// queued and processed asynchronously.
func (r *MonitorService) Run(ctx context.Context, monitorID string, opts ...option.RequestOption) (res *MonitorRunResponse, err error) {
opts = slices.Concat(r.options, opts)
if monitorID == "" {
err = errors.New("missing required monitor_id parameter")
return nil, err
}
path := fmt.Sprintf("monitors/%s/run", url.PathEscape(monitorID))
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...)
return res, err
}
type WebhookDelivery struct {
AttemptedAt time.Time `json:"attempted_at" api:"required" format:"date-time"`
Error WebhookDeliveryError `json:"error" api:"required"`
// The event this delivery carried. Deliveries recorded before event selection
// existed report change.detected.
//
// Any of "change.detected", "run.completed".
Event WebhookDeliveryEvent `json:"event" api:"required"`
// Identifier sent in the X-Context-Id header.
EventID string `json:"event_id" api:"required"`
// The endpoint's final HTTP response status, or null when no response was
// received.
HTTPStatus int64 `json:"http_status" api:"required"`
// Delivery outcome. delivered means any 2xx response; rejected means a non-2xx
// response; failed means no HTTP response was received; skipped_unsafe_url means
// the URL failed the public-endpoint safety check.
//
// Any of "delivered", "rejected", "failed", "skipped_unsafe_url".
Status WebhookDeliveryStatus `json:"status" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
AttemptedAt respjson.Field
Error respjson.Field
Event respjson.Field
EventID respjson.Field
HTTPStatus respjson.Field
Status respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r WebhookDelivery) RawJSON() string { return r.JSON.raw }
func (r *WebhookDelivery) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type WebhookDeliveryError struct {
Code string `json:"code" api:"required"`
Message string `json:"message" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Code respjson.Field
Message respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r WebhookDeliveryError) RawJSON() string { return r.JSON.raw }
func (r *WebhookDeliveryError) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// The event this delivery carried. Deliveries recorded before event selection
// existed report change.detected.
type WebhookDeliveryEvent string
const (
WebhookDeliveryEventChangeDetected WebhookDeliveryEvent = "change.detected"
WebhookDeliveryEventRunCompleted WebhookDeliveryEvent = "run.completed"
)
// Delivery outcome. delivered means any 2xx response; rejected means a non-2xx
// response; failed means no HTTP response was received; skipped_unsafe_url means
// the URL failed the public-endpoint safety check.
type WebhookDeliveryStatus string
const (
WebhookDeliveryStatusDelivered WebhookDeliveryStatus = "delivered"
WebhookDeliveryStatusRejected WebhookDeliveryStatus = "rejected"
WebhookDeliveryStatusFailed WebhookDeliveryStatus = "failed"
WebhookDeliveryStatusSkippedUnsafeURL WebhookDeliveryStatus = "skipped_unsafe_url"
)
// A web monitor. `mode` is the constant `web`; behavior is described by `target`
// (page/sitemap/extract) and `change_detection` (exact/semantic).
type MonitorNewResponse struct {
ID string `json:"id" api:"required"`
// Discriminated union describing how changes are detected.
ChangeDetection MonitorNewResponseChangeDetectionUnion `json:"change_detection" api:"required"`
CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
// Top-level monitor category. Always `web` today; the concrete behavior is
// described by `target` and `change_detection`.
//
// Any of "web".
Mode MonitorNewResponseMode `json:"mode" api:"required"`
Name string `json:"name" api:"required"`
// Run the monitor on a fixed interval defined by a frequency and a unit, e.g.
// every 6 hours or every 2 days. The total interval (frequency × unit) must be
// between 10 minutes and 1 year.
Schedule MonitorNewResponseSchedule `json:"schedule" api:"required"`
// Monitor lifecycle status. `failed` means the most recent run failed (see the
// monitor's `last_error`); failed monitors keep running on schedule and flip back
// to `active` on the next successful run. Monitors are auto-`paused` after
// repeated consecutive failures or insufficient-credit skips; resume by PATCHing
// status to `active`.
//
// Any of "active", "paused", "failed".
Status MonitorNewResponseStatus `json:"status" api:"required"`
// Discriminated union describing what the monitor watches.
Target MonitorNewResponseTargetUnion `json:"target" api:"required"`
UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
// Current baseline: the last observed value the monitor compares new snapshots
// against. Its shape follows `target.type` (page/sitemap/extract). Only populated
// on GET /monitors/{monitor_id}; null until the first baseline run completes (and
// after a target or change_detection update, which resets the baseline).
Baseline MonitorNewResponseBaselineUnion `json:"baseline" api:"nullable"`
LastChangeAt time.Time `json:"last_change_at" api:"nullable" format:"date-time"`
// Error from the most recent failed run; null when the last run succeeded.
LastError MonitorNewResponseLastError `json:"last_error" api:"nullable"`
LastRunAt time.Time `json:"last_run_at" api:"nullable" format:"date-time"`
// When the next scheduled run is due.
NextRunAt time.Time `json:"next_run_at" api:"nullable" format:"date-time"`
// User-defined tags for grouping and filtering monitors and their changes.
// Duplicates are removed.
Tags []string `json:"tags"`
Webhook MonitorNewResponseWebhook `json:"webhook" api:"nullable"`
// Present while webhook deliveries are failing consecutively; null when deliveries
// are healthy or no webhook is configured. Cleared on the next successful delivery
// and when the webhook URL changes.
WebhookFailure MonitorNewResponseWebhookFailure `json:"webhook_failure" api:"nullable"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
ChangeDetection respjson.Field
CreatedAt respjson.Field
Mode respjson.Field
Name respjson.Field
Schedule respjson.Field
Status respjson.Field
Target respjson.Field
UpdatedAt respjson.Field
Baseline respjson.Field
LastChangeAt respjson.Field
LastError respjson.Field
LastRunAt respjson.Field
NextRunAt respjson.Field
Tags respjson.Field
Webhook respjson.Field
WebhookFailure respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponse) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponse) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// MonitorNewResponseChangeDetectionUnion contains all possible properties and
// values from [MonitorNewResponseChangeDetectionExact],
// [MonitorNewResponseChangeDetectionSemantic].
//
// Use the [MonitorNewResponseChangeDetectionUnion.AsAny] method to switch on the
// variant.
//
// Use the methods beginning with 'As' to cast the union to one of its variants.
type MonitorNewResponseChangeDetectionUnion struct {
// Any of "exact", "semantic".
Type string `json:"type"`
// This field is from variant [MonitorNewResponseChangeDetectionSemantic].
ConfidenceThreshold float64 `json:"confidence_threshold"`
JSON struct {
Type respjson.Field
ConfidenceThreshold respjson.Field
raw string
} `json:"-"`
}
// anyMonitorNewResponseChangeDetection is implemented by each variant of
// [MonitorNewResponseChangeDetectionUnion] to add type safety for the return type
// of [MonitorNewResponseChangeDetectionUnion.AsAny]
type anyMonitorNewResponseChangeDetection interface {
implMonitorNewResponseChangeDetectionUnion()
}
func (MonitorNewResponseChangeDetectionExact) implMonitorNewResponseChangeDetectionUnion() {}
func (MonitorNewResponseChangeDetectionSemantic) implMonitorNewResponseChangeDetectionUnion() {}
// Use the following switch statement to find the correct variant
//
// switch variant := MonitorNewResponseChangeDetectionUnion.AsAny().(type) {
// case contextdev.MonitorNewResponseChangeDetectionExact:
// case contextdev.MonitorNewResponseChangeDetectionSemantic:
// default:
// fmt.Errorf("no variant present")
// }
func (u MonitorNewResponseChangeDetectionUnion) AsAny() anyMonitorNewResponseChangeDetection {
switch u.Type {
case "exact":
return u.AsExact()
case "semantic":
return u.AsSemantic()
}
return nil
}
func (u MonitorNewResponseChangeDetectionUnion) AsExact() (v MonitorNewResponseChangeDetectionExact) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
func (u MonitorNewResponseChangeDetectionUnion) AsSemantic() (v MonitorNewResponseChangeDetectionSemantic) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
// Returns the unmodified JSON received from the API
func (u MonitorNewResponseChangeDetectionUnion) RawJSON() string { return u.JSON.raw }
func (r *MonitorNewResponseChangeDetectionUnion) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Detect exact changes. For page targets, this means visible text diffs. For
// sitemap targets, this means URL additions and removals.
type MonitorNewResponseChangeDetectionExact struct {
Type constant.Exact `json:"type" default:"exact"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Type respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseChangeDetectionExact) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseChangeDetectionExact) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Detect meaning-level changes to tracked page content, ignoring cosmetic or
// paraphrase-only differences. Which changes are meaningful is judged against the
// extract target's `instructions` (and `schema`, when provided).
type MonitorNewResponseChangeDetectionSemantic struct {
Type constant.Semantic `json:"type" default:"semantic"`
ConfidenceThreshold float64 `json:"confidence_threshold"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Type respjson.Field
ConfidenceThreshold respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseChangeDetectionSemantic) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseChangeDetectionSemantic) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Top-level monitor category. Always `web` today; the concrete behavior is
// described by `target` and `change_detection`.
type MonitorNewResponseMode string
const (
MonitorNewResponseModeWeb MonitorNewResponseMode = "web"
)
// Run the monitor on a fixed interval defined by a frequency and a unit, e.g.
// every 6 hours or every 2 days. The total interval (frequency × unit) must be
// between 10 minutes and 1 year.
type MonitorNewResponseSchedule struct {
// Number of units between runs. The resulting interval (frequency × unit) must be
// at least 10 minutes and at most 1 year (e.g. minimum 10 when unit is minutes;
// maximum 365 when unit is days).
Frequency int64 `json:"frequency" api:"required"`
// Any of "interval".
Type string `json:"type" api:"required"`
// Any of "minutes", "hours", "days".
Unit string `json:"unit" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Frequency respjson.Field
Type respjson.Field
Unit respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseSchedule) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseSchedule) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Monitor lifecycle status. `failed` means the most recent run failed (see the
// monitor's `last_error`); failed monitors keep running on schedule and flip back
// to `active` on the next successful run. Monitors are auto-`paused` after
// repeated consecutive failures or insufficient-credit skips; resume by PATCHing
// status to `active`.
type MonitorNewResponseStatus string
const (
MonitorNewResponseStatusActive MonitorNewResponseStatus = "active"
MonitorNewResponseStatusPaused MonitorNewResponseStatus = "paused"
MonitorNewResponseStatusFailed MonitorNewResponseStatus = "failed"
)
// MonitorNewResponseTargetUnion contains all possible properties and values from
// [MonitorNewResponseTargetPage], [MonitorNewResponseTargetSitemap],
// [MonitorNewResponseTargetExtract].
//
// Use the [MonitorNewResponseTargetUnion.AsAny] method to switch on the variant.
//
// Use the methods beginning with 'As' to cast the union to one of its variants.
type MonitorNewResponseTargetUnion struct {
// Any of "page", "sitemap", "extract".
Type string `json:"type"`
URL string `json:"url"`
// This field is from variant [MonitorNewResponseTargetPage].
NormalizeWhitespace bool `json:"normalize_whitespace"`
// This field is from variant [MonitorNewResponseTargetSitemap].
Exclude []string `json:"exclude"`
// This field is from variant [MonitorNewResponseTargetSitemap].
Include []string `json:"include"`
// This field is from variant [MonitorNewResponseTargetSitemap].
MaxURLs int64 `json:"max_urls"`
// This field is from variant [MonitorNewResponseTargetExtract].
Instructions string `json:"instructions"`
// This field is from variant [MonitorNewResponseTargetExtract].
FollowSubdomains bool `json:"follow_subdomains"`
// This field is from variant [MonitorNewResponseTargetExtract].
MaxDepth int64 `json:"max_depth"`
// This field is from variant [MonitorNewResponseTargetExtract].
MaxPages int64 `json:"max_pages"`
// This field is from variant [MonitorNewResponseTargetExtract].
Schema map[string]any `json:"schema"`
JSON struct {
Type respjson.Field
URL respjson.Field
NormalizeWhitespace respjson.Field
Exclude respjson.Field
Include respjson.Field
MaxURLs respjson.Field
Instructions respjson.Field
FollowSubdomains respjson.Field
MaxDepth respjson.Field
MaxPages respjson.Field
Schema respjson.Field
raw string
} `json:"-"`
}
// anyMonitorNewResponseTarget is implemented by each variant of
// [MonitorNewResponseTargetUnion] to add type safety for the return type of
// [MonitorNewResponseTargetUnion.AsAny]
type anyMonitorNewResponseTarget interface {
implMonitorNewResponseTargetUnion()
}
func (MonitorNewResponseTargetPage) implMonitorNewResponseTargetUnion() {}
func (MonitorNewResponseTargetSitemap) implMonitorNewResponseTargetUnion() {}
func (MonitorNewResponseTargetExtract) implMonitorNewResponseTargetUnion() {}
// Use the following switch statement to find the correct variant
//
// switch variant := MonitorNewResponseTargetUnion.AsAny().(type) {
// case contextdev.MonitorNewResponseTargetPage:
// case contextdev.MonitorNewResponseTargetSitemap:
// case contextdev.MonitorNewResponseTargetExtract:
// default:
// fmt.Errorf("no variant present")
// }
func (u MonitorNewResponseTargetUnion) AsAny() anyMonitorNewResponseTarget {
switch u.Type {
case "page":
return u.AsPage()
case "sitemap":
return u.AsSitemap()
case "extract":
return u.AsExtract()
}
return nil
}
func (u MonitorNewResponseTargetUnion) AsPage() (v MonitorNewResponseTargetPage) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
func (u MonitorNewResponseTargetUnion) AsSitemap() (v MonitorNewResponseTargetSitemap) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
func (u MonitorNewResponseTargetUnion) AsExtract() (v MonitorNewResponseTargetExtract) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
// Returns the unmodified JSON received from the API
func (u MonitorNewResponseTargetUnion) RawJSON() string { return u.JSON.raw }
func (r *MonitorNewResponseTargetUnion) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Watch a single web page.
type MonitorNewResponseTargetPage struct {
Type constant.Page `json:"type" default:"page"`
URL string `json:"url" api:"required" format:"uri"`
// Normalize whitespace before comparing or analyzing text.
NormalizeWhitespace bool `json:"normalize_whitespace"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Type respjson.Field
URL respjson.Field
NormalizeWhitespace respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseTargetPage) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseTargetPage) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Watch a sitemap for URL additions and removals. Crawled URLs are normalized
// (lowercased host, no trailing slash/fragment) and scoped to the monitored site
// and its subdomains before comparison. On a detected difference the sitemap is
// re-fetched within the same run and only URLs both observations agree on are
// reported, suppressing transient crawl flaps.
type MonitorNewResponseTargetSitemap struct {
Type constant.Sitemap `json:"type" default:"sitemap"`
// Sitemap URL to monitor.
URL string `json:"url" api:"required" format:"uri"`
// URL path patterns to exclude (max 50).
Exclude []string `json:"exclude"`
// URL path patterns to include (max 50).
Include []string `json:"include"`
// Maximum number of sitemap URLs to track (capped at 10,000).
MaxURLs int64 `json:"max_urls"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Type respjson.Field
URL respjson.Field
Exclude respjson.Field
Include respjson.Field
MaxURLs respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseTargetSitemap) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseTargetSitemap) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Watch the monitor-relevant pages of a site for meaningful changes. A crawl
// guided by `schema`/`instructions` selects up to `max_pages` relevant pages to
// track; each run re-checks exactly those pages, and confirmed content changes are
// judged for relevance against the monitor's `instructions` (and `schema`, when
// provided). The tracked page set is refreshed by a periodic re-discovery crawl.
type MonitorNewResponseTargetExtract struct {
// Natural-language instructions guiding which pages and facts to track and which
// changes to report.
Instructions string `json:"instructions" api:"required"`
Type constant.Extract `json:"type" default:"extract"`
// Root URL to extract structured data from.
URL string `json:"url" api:"required" format:"uri"`
FollowSubdomains bool `json:"follow_subdomains"`
// Optional maximum link depth from the starting URL (0 = only the starting page).
MaxDepth int64 `json:"max_depth"`
// Maximum number of pages to track.
MaxPages int64 `json:"max_pages"`
// JSON Schema describing the data you care about. It is used three ways: it guides
// which pages are selected for tracking, it gives the change judge extra context
// on which changes matter (alongside `instructions`), and it defines the shape of
// the baseline `data` snapshot on GET /monitors/{monitor_id} (refreshed at most
// about once a day). It is not a response format for changes: change events and
// webhook payloads always contain diffs, summaries, and evidence excerpts — never
// data in this schema's shape. If omitted, a default summary + key-points schema
// is used.
Schema map[string]any `json:"schema"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Instructions respjson.Field
Type respjson.Field
URL respjson.Field
FollowSubdomains respjson.Field
MaxDepth respjson.Field
MaxPages respjson.Field
Schema respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseTargetExtract) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseTargetExtract) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// MonitorNewResponseBaselineUnion contains all possible properties and values from
// [MonitorNewResponseBaselinePageBaseline],
// [MonitorNewResponseBaselineSitemapBaseline],
// [MonitorNewResponseBaselineExtractBaseline].
//
// Use the methods beginning with 'As' to cast the union to one of its variants.
type MonitorNewResponseBaselineUnion struct {
CapturedAt time.Time `json:"captured_at"`
// This field is from variant [MonitorNewResponseBaselinePageBaseline].
Text string `json:"text"`
// This field is from variant [MonitorNewResponseBaselineSitemapBaseline].
URLCount int64 `json:"url_count"`
// This field is from variant [MonitorNewResponseBaselineSitemapBaseline].
URLs []string `json:"urls"`
// This field is from variant [MonitorNewResponseBaselineExtractBaseline].
Data any `json:"data"`
// This field is from variant [MonitorNewResponseBaselineExtractBaseline].
URLsAnalyzed []string `json:"urls_analyzed"`
JSON struct {
CapturedAt respjson.Field
Text respjson.Field
URLCount respjson.Field
URLs respjson.Field
Data respjson.Field
URLsAnalyzed respjson.Field
raw string
} `json:"-"`
}
func (u MonitorNewResponseBaselineUnion) AsPageBaseline() (v MonitorNewResponseBaselinePageBaseline) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
func (u MonitorNewResponseBaselineUnion) AsSitemapBaseline() (v MonitorNewResponseBaselineSitemapBaseline) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
func (u MonitorNewResponseBaselineUnion) AsExtractBaseline() (v MonitorNewResponseBaselineExtractBaseline) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
// Returns the unmodified JSON received from the API
func (u MonitorNewResponseBaselineUnion) RawJSON() string { return u.JSON.raw }
func (r *MonitorNewResponseBaselineUnion) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Current baseline of a `page` monitor: the visible page text as last observed.
type MonitorNewResponseBaselinePageBaseline struct {
// When this baseline was last captured or replaced.
CapturedAt time.Time `json:"captured_at" api:"required" format:"date-time"`
// The page's visible text as last observed.
Text string `json:"text" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
CapturedAt respjson.Field
Text respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseBaselinePageBaseline) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseBaselinePageBaseline) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Current baseline of a `sitemap` monitor: the normalized URL set as last
// observed.
type MonitorNewResponseBaselineSitemapBaseline struct {
// When this baseline was last captured or replaced.
CapturedAt time.Time `json:"captured_at" api:"required" format:"date-time"`
// Number of URLs in the baseline.
URLCount int64 `json:"url_count" api:"required"`
// The sitemap URLs as last observed (sorted, normalized).
URLs []string `json:"urls" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
CapturedAt respjson.Field
URLCount respjson.Field
URLs respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseBaselineSitemapBaseline) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseBaselineSitemapBaseline) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Current baseline of an `extract` monitor: the pages it tracks and the structured
// data as last extracted.
type MonitorNewResponseBaselineExtractBaseline struct {
// When this baseline was last captured or replaced.
CapturedAt time.Time `json:"captured_at" api:"required" format:"date-time"`
// The extracted structured data, matching the monitor's extraction schema (same
// shape as the /web/extract endpoint's `data`). Refreshed when the monitor
// re-discovers its page set (at most about once a day); `null` when no extraction
// has been captured yet.
Data any `json:"data" api:"required"`
// The page URLs the monitor tracks and analyzes for changes.
URLsAnalyzed []string `json:"urls_analyzed" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
CapturedAt respjson.Field
Data respjson.Field
URLsAnalyzed respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseBaselineExtractBaseline) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseBaselineExtractBaseline) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Error from the most recent failed run; null when the last run succeeded.
type MonitorNewResponseLastError struct {
Code string `json:"code" api:"required"`
Message string `json:"message" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Code respjson.Field
Message respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseLastError) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseLastError) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type MonitorNewResponseWebhook struct {
// Webhook URL events are delivered to.
URL string `json:"url" api:"required" format:"uri"`
// Events delivered to this endpoint. `change.detected` fires only when a run
// detects a change; `run.completed` fires on every completed run — including runs
// that detected no change — and embeds the change when one was detected. Defaults
// to `["change.detected"]` when omitted.
//
// Any of "change.detected", "run.completed".
Events []string `json:"events"`
// Signing secret used to verify webhook authenticity. Each delivery includes an
// `X-Context-Signature: t=<unix>,v1=<hmac>` header, where the HMAC is SHA-256 over
// `"{t}.{rawRequestBody}"` keyed by this secret. Recompute it with a constant-time
// compare and reject stale timestamps to prevent replay. Generated by the API;
// cannot be set by clients.
Secret string `json:"secret"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
URL respjson.Field
Events respjson.Field
Secret respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseWebhook) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseWebhook) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Present while webhook deliveries are failing consecutively; null when deliveries
// are healthy or no webhook is configured. Cleared on the next successful delivery
// and when the webhook URL changes.
type MonitorNewResponseWebhookFailure struct {
// Number of consecutive delivery attempts that did not succeed.
ConsecutiveFailures int64 `json:"consecutive_failures" api:"required"`
LastFailedAt time.Time `json:"last_failed_at" api:"required" format:"date-time"`
// Human-readable description of the most recent failure.
LastMessage string `json:"last_message" api:"required"`
// Outcome of the most recent failed delivery. rejected means a non-2xx response;
// failed means no HTTP response was received; skipped_unsafe_url means the URL
// failed the public-endpoint safety check.
//
// Any of "rejected", "failed", "skipped_unsafe_url".
LastStatus string `json:"last_status" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ConsecutiveFailures respjson.Field
LastFailedAt respjson.Field
LastMessage respjson.Field
LastStatus respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorNewResponseWebhookFailure) RawJSON() string { return r.JSON.raw }
func (r *MonitorNewResponseWebhookFailure) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// A web monitor. `mode` is the constant `web`; behavior is described by `target`
// (page/sitemap/extract) and `change_detection` (exact/semantic).
type MonitorGetResponse struct {
ID string `json:"id" api:"required"`
// Discriminated union describing how changes are detected.
ChangeDetection MonitorGetResponseChangeDetectionUnion `json:"change_detection" api:"required"`
CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
// Top-level monitor category. Always `web` today; the concrete behavior is
// described by `target` and `change_detection`.
//
// Any of "web".
Mode MonitorGetResponseMode `json:"mode" api:"required"`
Name string `json:"name" api:"required"`
// Run the monitor on a fixed interval defined by a frequency and a unit, e.g.
// every 6 hours or every 2 days. The total interval (frequency × unit) must be
// between 10 minutes and 1 year.
Schedule MonitorGetResponseSchedule `json:"schedule" api:"required"`
// Monitor lifecycle status. `failed` means the most recent run failed (see the
// monitor's `last_error`); failed monitors keep running on schedule and flip back
// to `active` on the next successful run. Monitors are auto-`paused` after
// repeated consecutive failures or insufficient-credit skips; resume by PATCHing
// status to `active`.
//
// Any of "active", "paused", "failed".
Status MonitorGetResponseStatus `json:"status" api:"required"`
// Discriminated union describing what the monitor watches.
Target MonitorGetResponseTargetUnion `json:"target" api:"required"`
UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
// Current baseline: the last observed value the monitor compares new snapshots
// against. Its shape follows `target.type` (page/sitemap/extract). Only populated
// on GET /monitors/{monitor_id}; null until the first baseline run completes (and
// after a target or change_detection update, which resets the baseline).
Baseline MonitorGetResponseBaselineUnion `json:"baseline" api:"nullable"`
LastChangeAt time.Time `json:"last_change_at" api:"nullable" format:"date-time"`
// Error from the most recent failed run; null when the last run succeeded.
LastError MonitorGetResponseLastError `json:"last_error" api:"nullable"`
LastRunAt time.Time `json:"last_run_at" api:"nullable" format:"date-time"`
// When the next scheduled run is due.
NextRunAt time.Time `json:"next_run_at" api:"nullable" format:"date-time"`
// User-defined tags for grouping and filtering monitors and their changes.
// Duplicates are removed.
Tags []string `json:"tags"`
Webhook MonitorGetResponseWebhook `json:"webhook" api:"nullable"`
// Present while webhook deliveries are failing consecutively; null when deliveries
// are healthy or no webhook is configured. Cleared on the next successful delivery
// and when the webhook URL changes.
WebhookFailure MonitorGetResponseWebhookFailure `json:"webhook_failure" api:"nullable"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
ChangeDetection respjson.Field
CreatedAt respjson.Field
Mode respjson.Field
Name respjson.Field
Schedule respjson.Field
Status respjson.Field
Target respjson.Field
UpdatedAt respjson.Field
Baseline respjson.Field
LastChangeAt respjson.Field
LastError respjson.Field
LastRunAt respjson.Field
NextRunAt respjson.Field
Tags respjson.Field
Webhook respjson.Field
WebhookFailure respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r MonitorGetResponse) RawJSON() string { return r.JSON.raw }
func (r *MonitorGetResponse) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// MonitorGetResponseChangeDetectionUnion contains all possible properties and
// values from [MonitorGetResponseChangeDetectionExact],
// [MonitorGetResponseChangeDetectionSemantic].
//
// Use the [MonitorGetResponseChangeDetectionUnion.AsAny] method to switch on the
// variant.
//
// Use the methods beginning with 'As' to cast the union to one of its variants.
type MonitorGetResponseChangeDetectionUnion struct {
// Any of "exact", "semantic".
Type string `json:"type"`
// This field is from variant [MonitorGetResponseChangeDetectionSemantic].
ConfidenceThreshold float64 `json:"confidence_threshold"`
JSON struct {
Type respjson.Field
ConfidenceThreshold respjson.Field
raw string
} `json:"-"`
}
// anyMonitorGetResponseChangeDetection is implemented by each variant of