Debian Codegraph @

jetstream/stream_config.go

raw
1 // Copyright 2022-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package jetstream
15
16 import (
17 "encoding/json"
18 "errors"
19 "fmt"
20 "strings"
21 "time"
22 )
23
24 type (
25 // StreamInfo shows config and current state for this stream.
26 StreamInfo struct {
27 // Config contains the configuration settings of the stream, set when
28 // creating or updating the stream.
29 Config StreamConfig `json:"config"`
30
31 // Created is the timestamp when the stream was created.
32 Created time.Time `json:"created"`
33
34 // State provides the state of the stream at the time of request,
35 // including metrics like the number of messages in the stream, total
36 // bytes, etc.
37 State StreamState `json:"state"`
38
39 // Cluster contains information about the cluster to which this stream
40 // belongs (if applicable).
41 Cluster *ClusterInfo `json:"cluster,omitempty"`
42
43 // Mirror contains information about another stream this one is
44 // mirroring. Mirroring is used to create replicas of another stream's
45 // data. This field is omitted if the stream is not mirroring another
46 // stream.
47 Mirror *StreamSourceInfo `json:"mirror,omitempty"`
48
49 // Sources is a list of source streams from which this stream collects
50 // data.
51 Sources []*StreamSourceInfo `json:"sources,omitempty"`
52
53 // TimeStamp indicates when the info was gathered by the server.
54 TimeStamp time.Time `json:"ts"`
55 }
56
57 // StreamConfig is the configuration of a JetStream stream.
58 StreamConfig struct {
59 // Name is the name of the stream. It is required and must be unique
60 // across the JetStream account.
61 //
62 // Name Names cannot contain whitespace, ., *, >, path separators
63 // (forward or backwards slash), and non-printable characters.
64 Name string `json:"name"`
65
66 // Description is an optional description of the stream.
67 Description string `json:"description,omitempty"`
68
69 // Subjects is a list of subjects that the stream is listening on.
70 // Wildcards are supported. Subjects cannot be set if the stream is
71 // created as a mirror.
72 Subjects []string `json:"subjects,omitempty"`
73
74 // Retention defines the message retention policy for the stream.
75 // Defaults to LimitsPolicy.
76 Retention RetentionPolicy `json:"retention"`
77
78 // MaxConsumers specifies the maximum number of consumers allowed for
79 // the stream.
80 MaxConsumers int `json:"max_consumers"`
81
82 // MaxMsgs is the maximum number of messages the stream will store.
83 // After reaching the limit, stream adheres to the discard policy.
84 // If not set, server default is -1 (unlimited).
85 MaxMsgs int64 `json:"max_msgs"`
86
87 // MaxBytes is the maximum total size of messages the stream will store.
88 // After reaching the limit, stream adheres to the discard policy.
89 // If not set, server default is -1 (unlimited).
90 MaxBytes int64 `json:"max_bytes"`
91
92 // Discard defines the policy for handling messages when the stream
93 // reaches its limits in terms of number of messages or total bytes.
94 Discard DiscardPolicy `json:"discard"`
95
96 // DiscardNewPerSubject is a flag to enable discarding new messages per
97 // subject when limits are reached. Requires DiscardPolicy to be
98 // DiscardNew and the MaxMsgsPerSubject to be set.
99 DiscardNewPerSubject bool `json:"discard_new_per_subject,omitempty"`
100
101 // MaxAge is the maximum age of messages that the stream will retain.
102 MaxAge time.Duration `json:"max_age"`
103
104 // MaxMsgsPerSubject is the maximum number of messages per subject that
105 // the stream will retain.
106 MaxMsgsPerSubject int64 `json:"max_msgs_per_subject"`
107
108 // MaxMsgSize is the maximum size of any single message in the stream.
109 MaxMsgSize int32 `json:"max_msg_size,omitempty"`
110
111 // Storage specifies the type of storage backend used for the stream
112 // (file or memory).
113 Storage StorageType `json:"storage"`
114
115 // Replicas is the number of stream replicas in clustered JetStream.
116 // Defaults to 1, maximum is 5.
117 Replicas int `json:"num_replicas"`
118
119 // NoAck is a flag to disable acknowledging messages received by this
120 // stream.
121 //
122 // If set to true, publish methods from the JetStream client will not
123 // work as expected, since they rely on acknowledgements. Core NATS
124 // publish methods should be used instead. Note that this will make
125 // message delivery less reliable.
126 NoAck bool `json:"no_ack,omitempty"`
127
128 // Duplicates is the window within which to track duplicate messages.
129 // If not set, server default is 2 minutes.
130 Duplicates time.Duration `json:"duplicate_window,omitempty"`
131
132 // Placement is used to declare where the stream should be placed via
133 // tags and/or an explicit cluster name.
134 Placement *Placement `json:"placement,omitempty"`
135
136 // Mirror defines the configuration for mirroring another stream.
137 Mirror *StreamSource `json:"mirror,omitempty"`
138
139 // Sources is a list of other streams this stream sources messages from.
140 Sources []*StreamSource `json:"sources,omitempty"`
141
142 // Sealed streams do not allow messages to be published or deleted via limits or API,
143 // sealed streams can not be unsealed via configuration update. Can only
144 // be set on already created streams via the Update API.
145 Sealed bool `json:"sealed,omitempty"`
146
147 // DenyDelete restricts the ability to delete messages from a stream via
148 // the API. Defaults to false.
149 DenyDelete bool `json:"deny_delete,omitempty"`
150
151 // DenyPurge restricts the ability to purge messages from a stream via
152 // the API. Defaults to false.
153 DenyPurge bool `json:"deny_purge,omitempty"`
154
155 // AllowRollup allows the use of the Nats-Rollup header to replace all
156 // contents of a stream, or subject in a stream, with a single new
157 // message.
158 AllowRollup bool `json:"allow_rollup_hdrs,omitempty"`
159
160 // Compression specifies the message storage compression algorithm.
161 // Defaults to NoCompression.
162 Compression StoreCompression `json:"compression"`
163
164 // FirstSeq is the initial sequence number of the first message in the
165 // stream.
166 FirstSeq uint64 `json:"first_seq,omitempty"`
167
168 // SubjectTransform allows applying a transformation to matching
169 // messages' subjects.
170 SubjectTransform *SubjectTransformConfig `json:"subject_transform,omitempty"`
171
172 // RePublish allows immediate republishing a message to the configured
173 // subject after it's stored.
174 RePublish *RePublish `json:"republish,omitempty"`
175
176 // AllowDirect enables direct access to individual messages using direct
177 // get API. Defaults to false.
178 AllowDirect bool `json:"allow_direct"`
179
180 // MirrorDirect enables direct access to individual messages from the
181 // origin stream using direct get API. Defaults to false.
182 MirrorDirect bool `json:"mirror_direct"`
183
184 // ConsumerLimits defines limits of certain values that consumers can
185 // set, defaults for those who don't set these settings
186 ConsumerLimits StreamConsumerLimits `json:"consumer_limits,omitempty"`
187
188 // Metadata is a set of application-defined key-value pairs for
189 // associating metadata on the stream. This feature requires nats-server
190 // v2.10.0 or later.
191 Metadata map[string]string `json:"metadata,omitempty"`
192
193 // Template identifies the template that manages the Stream.
194 // Deprecated: This feature is no longer supported.
195 Template string `json:"template_owner,omitempty"`
196
197 // AllowMsgTTL allows header initiated per-message TTLs.
198 // This feature requires nats-server v2.11.0 or later.
199 AllowMsgTTL bool `json:"allow_msg_ttl,omitempty"`
200
201 // Enables and sets a duration for adding server markers for delete, purge and max age limits.
202 // This feature requires nats-server v2.11.0 or later.
203 SubjectDeleteMarkerTTL time.Duration `json:"subject_delete_marker_ttl,omitempty"`
204
205 // AllowMsgCounter enables the feature
206 AllowMsgCounter bool `json:"allow_msg_counter,omitempty"`
207
208 // AllowAtomicPublish allows atomic batch publishing into the stream.
209 AllowAtomicPublish bool `json:"allow_atomic,omitempty"`
210
211 // AllowMsgSchedules enables the scheduling of messages
212 AllowMsgSchedules bool `json:"allow_msg_schedules,omitempty"`
213
214 // PersistMode allows to opt-in to different persistence mode settings.
215 PersistMode PersistModeType `json:"persist_mode,omitempty"`
216
217 // AllowBatchPublish allows fast batch publishing into the stream.
218 // This feature requires nats-server v2.14.0 or later.
219 AllowBatchPublish bool `json:"allow_batched,omitempty"`
220 }
221
222 // StreamSourceInfo shows information about an upstream stream
223 // source/mirror.
224 StreamSourceInfo struct {
225 // Name is the name of the stream that is being replicated.
226 Name string `json:"name"`
227
228 // Lag informs how many messages behind the source/mirror operation is.
229 // This will only show correctly if there is active communication
230 // with stream/mirror.
231 Lag uint64 `json:"lag"`
232
233 // Seq is the last message sequence seen from the source stream. Not
234 // reported for mirrors.
235 Seq uint64 `json:"seq,omitempty"`
236
237 // Active informs when last the mirror or sourced stream had activity.
238 // Value will be -1 when there has been no activity.
239 Active time.Duration `json:"active"`
240
241 // FilterSubject is the subject filter defined for this source/mirror.
242 FilterSubject string `json:"filter_subject,omitempty"`
243
244 // SubjectTransforms is a list of subject transforms defined for this
245 // source/mirror.
246 SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"`
247 }
248
249 // StreamState is the state of a JetStream stream at the time of request.
250 StreamState struct {
251 // Msgs is the number of messages stored in the stream.
252 Msgs uint64 `json:"messages"`
253
254 // Bytes is the number of bytes stored in the stream.
255 Bytes uint64 `json:"bytes"`
256
257 // FirstSeq is the sequence number of the first message in the stream.
258 FirstSeq uint64 `json:"first_seq"`
259
260 // FirstTime is the timestamp of the first message in the stream.
261 FirstTime time.Time `json:"first_ts"`
262
263 // LastSeq is the sequence number of the last message in the stream.
264 LastSeq uint64 `json:"last_seq"`
265
266 // LastTime is the timestamp of the last message in the stream.
267 LastTime time.Time `json:"last_ts"`
268
269 // Consumers is the number of consumers on the stream.
270 Consumers int `json:"consumer_count"`
271
272 // Deleted is a list of sequence numbers that have been removed from the
273 // stream. This field will only be returned if the stream has been
274 // fetched with the DeletedDetails option.
275 Deleted []uint64 `json:"deleted"`
276
277 // NumDeleted is the number of messages that have been removed from the
278 // stream. Only deleted messages causing a gap in stream sequence numbers
279 // are counted. Messages deleted at the beginning or end of the stream
280 // are not counted.
281 NumDeleted int `json:"num_deleted"`
282
283 // NumSubjects is the number of unique subjects the stream has received
284 // messages on.
285 NumSubjects uint64 `json:"num_subjects"`
286
287 // Subjects is a map of subjects the stream has received messages on
288 // with message count per subject. This field will only be returned if
289 // the stream has been fetched with the SubjectFilter option.
290 Subjects map[string]uint64 `json:"subjects"`
291 }
292
293 // ClusterInfo shows information about the underlying set of servers that
294 // make up the stream or consumer.
295 ClusterInfo struct {
296 // Name is the name of the cluster.
297 Name string `json:"name,omitempty"`
298
299 // RaftGroup is the name of the Raft group managing the asset (in
300 // clustered environments).
301 RaftGroup string `json:"raft_group,omitempty"`
302
303 // Leader is the server name of the RAFT leader.
304 Leader string `json:"leader,omitempty"`
305
306 // LeaderSince is the time that it was elected as leader in RFC3339
307 // format, absent when not the leader.
308 LeaderSince *time.Time `json:"leader_since,omitempty"`
309
310 // SystemAcc indicates if the traffic_account is the system account.
311 // When true, replication traffic goes over the system account.
312 SystemAcc bool `json:"system_account,omitempty"`
313
314 // TrafficAcc is the account where the replication traffic goes over.
315 TrafficAcc string `json:"traffic_account,omitempty"`
316
317 // Replicas is the list of members of the RAFT cluster.
318 Replicas []*PeerInfo `json:"replicas,omitempty"`
319
320 // Desired is the desired set of servers that should make up the
321 // stream or consumer. Absent when no reconfiguration is in progress.
322 Desired *DesiredClusterInfo `json:"desired,omitempty"`
323 }
324
325 // DesiredClusterInfo shows the desired set of servers that should make up
326 // the stream or consumer.
327 DesiredClusterInfo struct {
328 // Created is when the desired state was recorded on the assignment.
329 Created time.Time `json:"created"`
330
331 // Name is the name of the target cluster the group should end up in.
332 Name string `json:"name,omitempty"`
333
334 // Replicas are the peers chosen to be the final peer set, whereas
335 // ClusterInfo.Replicas holds the peers that currently host the stream
336 // or consumer. Absent while scaling down until the final peer set is
337 // selected.
338 Replicas []*DesiredPeerInfo `json:"replicas,omitempty"`
339
340 // Origin is the configuration the reconfiguration can be rolled back
341 // to if it is canceled.
342 Origin *DesiredClusterInfoOrigin `json:"origin,omitempty"`
343
344 // Status is what the group leader is currently doing to reach the
345 // desired state, or what it is waiting on.
346 Status *DesiredClusterInfoStatus `json:"status,omitempty"`
347 }
348
349 // DesiredClusterInfoOrigin is the configuration the reconfiguration can
350 // be rolled back to if it is canceled.
351 DesiredClusterInfoOrigin struct {
352 // Replicas is the original replicas before it was updated.
353 Replicas int `json:"replicas"`
354
355 // Placement is the original placement before it was updated.
356 Placement *Placement `json:"placement,omitempty"`
357
358 // Retention remains active while changing between retention
359 // policies, until unset.
360 Retention *RetentionPolicy `json:"retention,omitempty"`
361 }
362
363 // DesiredPeerInfo is a minimal version of PeerInfo describing a peer in
364 // the desired peer set.
365 DesiredPeerInfo struct {
366 // Name is the unique name for the peer.
367 Name string `json:"name"`
368
369 // Offline indicates the peer has not been seen recently.
370 Offline bool `json:"offline,omitempty"`
371
372 // Peer is the unique ID for the peer.
373 Peer string `json:"peer"`
374 }
375
376 // DesiredClusterInfoStatus is what the group leader is currently doing to
377 // reach the desired state, or what it is waiting on.
378 DesiredClusterInfoStatus struct {
379 // Description is a short status line describing what the group leader
380 // is currently doing to move this group toward its desired state, or
381 // what it is waiting on.
382 Description string `json:"description"`
383
384 // Type classifies the description by what has to change for the
385 // migration to advance, so it can be matched on without parsing the
386 // status line.
387 Type MigrationStatusType `json:"type"`
388
389 // Err is the underlying failure behind this status, if it had one.
390 // Only set for faults that persist across cycles, never for races
391 // that resolve themselves.
392 Err string `json:"err,omitempty"`
393 }
394
395 // PeerInfo shows information about the peers in the cluster that are
396 // supporting the stream or consumer.
397 PeerInfo struct {
398 // Name is the server name of the peer.
399 Name string `json:"name"`
400
401 // Current indicates if the peer is up to date and synchronized with the
402 // leader.
403 Current bool `json:"current"`
404
405 // Offline indicates if the peer is considered offline by the group.
406 Offline bool `json:"offline,omitempty"`
407
408 // Active it the duration since this peer was last seen.
409 Active time.Duration `json:"active"`
410
411 // Lag is the number of uncommitted operations this peer is behind the
412 // leader.
413 Lag uint64 `json:"lag,omitempty"`
414
415 // Peer is the unique ID for the peer.
416 Peer string `json:"peer"`
417
418 // Pending indicates the peer is part of the assignment, but is not a
419 // peer of the Raft group yet or is being removed.
420 Pending bool `json:"pending,omitempty"`
421 }
422
423 // SubjectTransformConfig is for applying a subject transform (to matching
424 // messages) before doing anything else when a new message is received.
425 SubjectTransformConfig struct {
426 // Source is the subject pattern to match incoming messages against.
427 Source string `json:"src"`
428
429 // Destination is the subject pattern to remap the subject to.
430 Destination string `json:"dest"`
431 }
432
433 // RePublish is for republishing messages once committed to a stream. The
434 // original subject is remapped from the subject pattern to the destination
435 // pattern.
436 RePublish struct {
437 // Source is the subject pattern to match incoming messages against.
438 Source string `json:"src,omitempty"`
439
440 // Destination is the subject pattern to republish the subject to.
441 Destination string `json:"dest"`
442
443 // HeadersOnly is a flag to indicate that only the headers should be
444 // republished.
445 HeadersOnly bool `json:"headers_only,omitempty"`
446 }
447
448 // Placement is used to guide placement of streams in clustered JetStream.
449 Placement struct {
450 // Cluster is the name of the cluster to which the stream should be
451 // assigned.
452 Cluster string `json:"cluster"`
453
454 // Tags are used to match streams to servers in the cluster. A stream
455 // will be assigned to a server with a matching tag.
456 Tags []string `json:"tags,omitempty"`
457 }
458
459 // StreamSource dictates how streams can source from other streams.
460 StreamSource struct {
461 // Name is the name of the stream to source from.
462 Name string `json:"name"`
463
464 // OptStartSeq is the sequence number to start sourcing from.
465 OptStartSeq uint64 `json:"opt_start_seq,omitempty"`
466
467 // OptStartTime is the timestamp of messages to start sourcing from.
468 OptStartTime *time.Time `json:"opt_start_time,omitempty"`
469
470 // FilterSubject is the subject filter used to only replicate messages
471 // with matching subjects.
472 FilterSubject string `json:"filter_subject,omitempty"`
473
474 // SubjectTransforms is a list of subject transforms to apply to
475 // matching messages.
476 //
477 // Subject transforms on sources and mirrors are also used as subject
478 // filters with optional transformations.
479 SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"`
480
481 // External is a configuration referencing a stream source in another
482 // account or JetStream domain.
483 External *ExternalStream `json:"external,omitempty"`
484
485 // Consumer is consumer information for durable sourcing.
486 //
487 // This feature requires nats-server v2.14.0 or later.
488 Consumer *StreamConsumerSource `json:"consumer,omitempty"`
489
490 // Domain is used to configure a stream source in another JetStream
491 // domain. This setting will set the External field with the appropriate
492 // APIPrefix.
493 Domain string `json:"-"`
494 }
495
496 // StreamConsumerSource is consumer information for durable sourcing.
497 //
498 // This feature requires nats-server v2.14.0 or later.
499 StreamConsumerSource struct {
500 // Name is the consumer name.
501 Name string `json:"name,omitempty"`
502
503 // DeliverSubject is the subject to deliver messages to.
504 DeliverSubject string `json:"deliver_subject,omitempty"`
505 }
506
507 // ExternalStream allows you to qualify access to a stream source in another
508 // account.
509 ExternalStream struct {
510 // APIPrefix is the subject prefix that imports the other account/domain
511 // $JS.API.CONSUMER.> subjects.
512 APIPrefix string `json:"api"`
513
514 // DeliverPrefix is the delivery subject to use for the push consumer.
515 DeliverPrefix string `json:"deliver"`
516 }
517
518 // StreamConsumerLimits are the limits for a consumer on a stream. These can
519 // be overridden on a per consumer basis.
520 StreamConsumerLimits struct {
521 // InactiveThreshold is a duration which instructs the server to clean
522 // up the consumer if it has been inactive for the specified duration.
523 InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
524
525 // MaxAckPending is a maximum number of outstanding unacknowledged
526 // messages for a consumer.
527 MaxAckPending int `json:"max_ack_pending,omitempty"`
528 }
529
530 // DiscardPolicy determines how to proceed when limits of messages or bytes
531 // are reached.
532 DiscardPolicy int
533
534 // RetentionPolicy determines how messages in a stream are retained.
535 RetentionPolicy int
536
537 // StorageType determines how messages are stored for retention.
538 StorageType int
539
540 // StoreCompression determines how messages are compressed.
541 StoreCompression uint8
542
543 // PersistModeType determines what persistence mode the stream uses.
544 PersistModeType int
545
546 // MigrationStatusType classifies a migration status by what has to
547 // change for the migration to advance.
548 MigrationStatusType string
549 )
550
551 const (
552 // MigrationStatusMeta means the meta leader must record or advance the
553 // desired state.
554 MigrationStatusMeta MigrationStatusType = "meta"
555
556 // MigrationStatusMembership means a proposed membership change must
557 // commit.
558 MigrationStatusMembership MigrationStatusType = "membership"
559
560 // MigrationStatusSnapshot means a snapshot must be installed.
561 MigrationStatusSnapshot MigrationStatusType = "snapshot"
562
563 // MigrationStatusCatchup means more peers must catch up before one can
564 // be removed.
565 MigrationStatusCatchup MigrationStatusType = "catchup"
566
567 // MigrationStatusQuorum means more peers must come online before acting
568 // without losing quorum.
569 MigrationStatusQuorum MigrationStatusType = "quorum"
570
571 // MigrationStatusBlocked means another asset must move first.
572 MigrationStatusBlocked MigrationStatusType = "blocked"
573
574 // MigrationStatusUnavailable means there is nothing to do: shutting down,
575 // or the assignment is gone.
576 MigrationStatusUnavailable MigrationStatusType = "unavailable"
577 )
578
579 const (
580 // LimitsPolicy (default) means that messages are retained until any given
581 // limit is reached. This could be one of MaxMsgs, MaxBytes, or MaxAge.
582 LimitsPolicy RetentionPolicy = iota
583
584 // InterestPolicy specifies that when all known observables have
585 // acknowledged a message it can be removed.
586 InterestPolicy
587
588 // WorkQueuePolicy specifies that when the first worker or subscriber
589 // acknowledges the message it can be removed.
590 WorkQueuePolicy
591 )
592
593 const (
594 // DiscardOld will remove older messages to return to the limits. This is
595 // the default.
596 DiscardOld DiscardPolicy = iota
597
598 // DiscardNew will fail to store new messages once the limits are reached.
599 DiscardNew
600 )
601
602 const (
603 limitsPolicyString = "limits"
604 interestPolicyString = "interest"
605 workQueuePolicyString = "workqueue"
606 )
607
608 const (
609 // DefaultPersistMode specifies the default persist mode. Writes to the stream will immediately be flushed.
610 // The publish acknowledgement will be sent after the persisting completes.
611 DefaultPersistMode = PersistModeType(iota)
612 // AsyncPersistMode specifies writes to the stream will be flushed asynchronously.
613 // The publish acknowledgement may be sent before the persisting completes.
614 // This means writes could be lost if they weren't flushed prior to a hard kill of the server.
615 AsyncPersistMode
616 )
617
618 func (rp RetentionPolicy) String() string {
619 switch rp {
620 case LimitsPolicy:
621 return "Limits"
622 case InterestPolicy:
623 return "Interest"
624 case WorkQueuePolicy:
625 return "WorkQueue"
626 default:
627 return "Unknown Retention Policy"
628 }
629 }
630
631 func (rp RetentionPolicy) MarshalJSON() ([]byte, error) {
632 switch rp {
633 case LimitsPolicy:
634 return json.Marshal(limitsPolicyString)
635 case InterestPolicy:
636 return json.Marshal(interestPolicyString)
637 case WorkQueuePolicy:
638 return json.Marshal(workQueuePolicyString)
639 default:
640 return nil, fmt.Errorf("nats: can not marshal %v", rp)
641 }
642 }
643
644 func (rp *RetentionPolicy) UnmarshalJSON(data []byte) error {
645 switch string(data) {
646 case jsonString(limitsPolicyString):
647 *rp = LimitsPolicy
648 case jsonString(interestPolicyString):
649 *rp = InterestPolicy
650 case jsonString(workQueuePolicyString):
651 *rp = WorkQueuePolicy
652 default:
653 return fmt.Errorf("nats: can not unmarshal %q", data)
654 }
655 return nil
656 }
657
658 func (dp DiscardPolicy) String() string {
659 switch dp {
660 case DiscardOld:
661 return "DiscardOld"
662 case DiscardNew:
663 return "DiscardNew"
664 default:
665 return "Unknown Discard Policy"
666 }
667 }
668
669 func (dp DiscardPolicy) MarshalJSON() ([]byte, error) {
670 switch dp {
671 case DiscardOld:
672 return json.Marshal("old")
673 case DiscardNew:
674 return json.Marshal("new")
675 default:
676 return nil, fmt.Errorf("nats: can not marshal %v", dp)
677 }
678 }
679
680 func (dp *DiscardPolicy) UnmarshalJSON(data []byte) error {
681 switch strings.ToLower(string(data)) {
682 case jsonString("old"):
683 *dp = DiscardOld
684 case jsonString("new"):
685 *dp = DiscardNew
686 default:
687 return fmt.Errorf("nats: can not unmarshal %q", data)
688 }
689 return nil
690 }
691
692 func (pm PersistModeType) String() string {
693 switch pm {
694 case DefaultPersistMode:
695 return "Default"
696 case AsyncPersistMode:
697 return "Async"
698 default:
699 return "Unknown Persist Mode"
700 }
701 }
702
703 func (pm PersistModeType) MarshalJSON() ([]byte, error) {
704 switch pm {
705 case DefaultPersistMode:
706 return json.Marshal("default")
707 case AsyncPersistMode:
708 return json.Marshal("async")
709 default:
710 return nil, fmt.Errorf("nats: can not marshal %v", pm)
711 }
712 }
713
714 func (pm *PersistModeType) UnmarshalJSON(data []byte) error {
715 switch strings.ToLower(string(data)) {
716 case jsonString("default"):
717 *pm = DefaultPersistMode
718 case jsonString("async"):
719 *pm = AsyncPersistMode
720 default:
721 return fmt.Errorf("nats: can not unmarshal %q", data)
722 }
723 return nil
724 }
725
726 const (
727 // FileStorage specifies on disk storage. It's the default.
728 FileStorage StorageType = iota
729 // MemoryStorage specifies in memory only.
730 MemoryStorage
731 )
732
733 const (
734 memoryStorageString = "memory"
735 fileStorageString = "file"
736 )
737
738 func (st StorageType) String() string {
739 switch st {
740 case MemoryStorage:
741 return "Memory"
742 case FileStorage:
743 return "File"
744 default:
745 return "Unknown Storage Type"
746 }
747 }
748
749 func (st StorageType) MarshalJSON() ([]byte, error) {
750 switch st {
751 case MemoryStorage:
752 return json.Marshal(memoryStorageString)
753 case FileStorage:
754 return json.Marshal(fileStorageString)
755 default:
756 return nil, fmt.Errorf("nats: can not marshal %v", st)
757 }
758 }
759
760 func (st *StorageType) UnmarshalJSON(data []byte) error {
761 switch string(data) {
762 case jsonString(memoryStorageString):
763 *st = MemoryStorage
764 case jsonString(fileStorageString):
765 *st = FileStorage
766 default:
767 return fmt.Errorf("nats: can not unmarshal %q", data)
768 }
769 return nil
770 }
771
772 func jsonString(s string) string {
773 return "\"" + s + "\""
774 }
775
776 const (
777 // NoCompression disables compression on the stream. This is the default.
778 NoCompression StoreCompression = iota
779
780 // S2Compression enables S2 compression on the stream.
781 S2Compression
782 )
783
784 func (alg StoreCompression) String() string {
785 switch alg {
786 case NoCompression:
787 return "None"
788 case S2Compression:
789 return "S2"
790 default:
791 return "Unknown StoreCompression"
792 }
793 }
794
795 func (alg StoreCompression) MarshalJSON() ([]byte, error) {
796 var str string
797 switch alg {
798 case S2Compression:
799 str = "s2"
800 case NoCompression:
801 str = "none"
802 default:
803 return nil, errors.New("unknown compression algorithm")
804 }
805 return json.Marshal(str)
806 }
807
808 func (alg *StoreCompression) UnmarshalJSON(b []byte) error {
809 var str string
810 if err := json.Unmarshal(b, &str); err != nil {
811 return err
812 }
813 switch str {
814 case "s2":
815 *alg = S2Compression
816 case "none":
817 *alg = NoCompression
818 default:
819 return errors.New("unknown compression algorithm")
820 }
821 return nil
822 }