| 1 |
// Copyright 2020-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 server |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"cmp" |
| 19 |
"encoding/json" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"io" |
| 23 |
"maps" |
| 24 |
"os" |
| 25 |
"path/filepath" |
| 26 |
"runtime" |
| 27 |
"slices" |
| 28 |
"strings" |
| 29 |
"sync" |
| 30 |
"sync/atomic" |
| 31 |
"time" |
| 32 |
|
| 33 |
"github.com/nats-io/nuid" |
| 34 |
) |
| 35 |
|
| 36 |
// Request API subjects for JetStream. |
| 37 |
const ( |
| 38 |
// All API endpoints. |
| 39 |
jsAllAPI = "$JS.API.>" |
| 40 |
|
| 41 |
// For constructing JetStream domain prefixes. |
| 42 |
jsDomainAPI = "$JS.%s.API.>" |
| 43 |
|
| 44 |
JSApiPrefix = "$JS.API" |
| 45 |
|
| 46 |
// JSApiAccountInfo is for obtaining general information about JetStream for this account. |
| 47 |
// Will return JSON response. |
| 48 |
JSApiAccountInfo = "$JS.API.INFO" |
| 49 |
|
| 50 |
// JSApiStreamCreate is the endpoint to create new streams. |
| 51 |
// Will return JSON response. |
| 52 |
JSApiStreamCreate = "$JS.API.STREAM.CREATE.*" |
| 53 |
JSApiStreamCreateT = "$JS.API.STREAM.CREATE.%s" |
| 54 |
|
| 55 |
// JSApiStreamUpdate is the endpoint to update existing streams. |
| 56 |
// Will return JSON response. |
| 57 |
JSApiStreamUpdate = "$JS.API.STREAM.UPDATE.*" |
| 58 |
JSApiStreamUpdateT = "$JS.API.STREAM.UPDATE.%s" |
| 59 |
|
| 60 |
// JSApiStreams is the endpoint to list all stream names for this account. |
| 61 |
// Will return JSON response. |
| 62 |
JSApiStreams = "$JS.API.STREAM.NAMES" |
| 63 |
// JSApiStreamList is the endpoint that will return all detailed stream information |
| 64 |
JSApiStreamList = "$JS.API.STREAM.LIST" |
| 65 |
|
| 66 |
// JSApiStreamInfo is for obtaining general information about a named stream. |
| 67 |
// Will return JSON response. |
| 68 |
JSApiStreamInfo = "$JS.API.STREAM.INFO.*" |
| 69 |
JSApiStreamInfoT = "$JS.API.STREAM.INFO.%s" |
| 70 |
|
| 71 |
// JSApiStreamDelete is the endpoint to delete streams. |
| 72 |
// Will return JSON response. |
| 73 |
JSApiStreamDelete = "$JS.API.STREAM.DELETE.*" |
| 74 |
JSApiStreamDeleteT = "$JS.API.STREAM.DELETE.%s" |
| 75 |
|
| 76 |
// JSApiStreamPurge is the endpoint to purge streams. |
| 77 |
// Will return JSON response. |
| 78 |
JSApiStreamPurge = "$JS.API.STREAM.PURGE.*" |
| 79 |
JSApiStreamPurgeT = "$JS.API.STREAM.PURGE.%s" |
| 80 |
|
| 81 |
// JSApiStreamSnapshot is the endpoint to snapshot streams. |
| 82 |
// Will return a stream of chunks with a nil chunk as EOF to |
| 83 |
// the deliver subject. Caller should respond to each chunk |
| 84 |
// with a nil body response for ack flow. |
| 85 |
JSApiStreamSnapshot = "$JS.API.STREAM.SNAPSHOT.*" |
| 86 |
JSApiStreamSnapshotT = "$JS.API.STREAM.SNAPSHOT.%s" |
| 87 |
|
| 88 |
// JSApiStreamRestore is the endpoint to restore a stream from a snapshot. |
| 89 |
// Caller should respond to each chunk with a nil body response. |
| 90 |
JSApiStreamRestore = "$JS.API.STREAM.RESTORE.*" |
| 91 |
JSApiStreamRestoreT = "$JS.API.STREAM.RESTORE.%s" |
| 92 |
|
| 93 |
// JSApiMsgDelete is the endpoint to delete messages from a stream. |
| 94 |
// Will return JSON response. |
| 95 |
JSApiMsgDelete = "$JS.API.STREAM.MSG.DELETE.*" |
| 96 |
JSApiMsgDeleteT = "$JS.API.STREAM.MSG.DELETE.%s" |
| 97 |
|
| 98 |
// JSApiMsgGet is the template for direct requests for a message by its stream sequence number. |
| 99 |
// Will return JSON response. |
| 100 |
JSApiMsgGet = "$JS.API.STREAM.MSG.GET.*" |
| 101 |
JSApiMsgGetT = "$JS.API.STREAM.MSG.GET.%s" |
| 102 |
|
| 103 |
// JSDirectMsgGet is the template for non-api layer direct requests for a message by its stream sequence number or last by subject. |
| 104 |
// Will return the message similar to how a consumer receives the message, no JSON processing. |
| 105 |
// If the message can not be found we will use a status header of 404. If the stream does not exist the client will get a no-responders or timeout. |
| 106 |
JSDirectMsgGet = "$JS.API.DIRECT.GET.*" |
| 107 |
JSDirectMsgGetT = "$JS.API.DIRECT.GET.%s" |
| 108 |
|
| 109 |
// This is a direct version of get last by subject, which will be the dominant pattern for KV access once 2.9 is released. |
| 110 |
// The stream and the key will be part of the subject to allow for no-marshal payloads and subject based security permissions. |
| 111 |
JSDirectGetLastBySubject = "$JS.API.DIRECT.GET.*.>" |
| 112 |
JSDirectGetLastBySubjectT = "$JS.API.DIRECT.GET.%s.%s" |
| 113 |
|
| 114 |
// jsDirectGetPre |
| 115 |
jsDirectGetPre = "$JS.API.DIRECT.GET" |
| 116 |
|
| 117 |
// JSApiConsumerCreate is the endpoint to create consumers for streams. |
| 118 |
// This was also the legacy endpoint for ephemeral consumers. |
| 119 |
// It now can take consumer name and optional filter subject, which when part of the subject controls access. |
| 120 |
// Will return JSON response. |
| 121 |
JSApiConsumerCreate = "$JS.API.CONSUMER.CREATE.*" |
| 122 |
JSApiConsumerCreateT = "$JS.API.CONSUMER.CREATE.%s" |
| 123 |
JSApiConsumerCreateEx = "$JS.API.CONSUMER.CREATE.*.>" |
| 124 |
JSApiConsumerCreateExT = "$JS.API.CONSUMER.CREATE.%s.%s.%s" |
| 125 |
|
| 126 |
// JSApiDurableCreate is the endpoint to create durable consumers for streams. |
| 127 |
// You need to include the stream and consumer name in the subject. |
| 128 |
JSApiDurableCreate = "$JS.API.CONSUMER.DURABLE.CREATE.*.*" |
| 129 |
JSApiDurableCreateT = "$JS.API.CONSUMER.DURABLE.CREATE.%s.%s" |
| 130 |
|
| 131 |
// JSApiConsumers is the endpoint to list all consumer names for the stream. |
| 132 |
// Will return JSON response. |
| 133 |
JSApiConsumers = "$JS.API.CONSUMER.NAMES.*" |
| 134 |
JSApiConsumersT = "$JS.API.CONSUMER.NAMES.%s" |
| 135 |
|
| 136 |
// JSApiConsumerList is the endpoint that will return all detailed consumer information |
| 137 |
JSApiConsumerList = "$JS.API.CONSUMER.LIST.*" |
| 138 |
JSApiConsumerListT = "$JS.API.CONSUMER.LIST.%s" |
| 139 |
|
| 140 |
// JSApiConsumerInfo is for obtaining general information about a consumer. |
| 141 |
// Will return JSON response. |
| 142 |
JSApiConsumerInfo = "$JS.API.CONSUMER.INFO.*.*" |
| 143 |
JSApiConsumerInfoT = "$JS.API.CONSUMER.INFO.%s.%s" |
| 144 |
|
| 145 |
// JSApiConsumerDelete is the endpoint to delete consumers. |
| 146 |
// Will return JSON response. |
| 147 |
JSApiConsumerDelete = "$JS.API.CONSUMER.DELETE.*.*" |
| 148 |
JSApiConsumerDeleteT = "$JS.API.CONSUMER.DELETE.%s.%s" |
| 149 |
|
| 150 |
// JSApiConsumerPause is the endpoint to pause or unpause consumers. |
| 151 |
// Will return JSON response. |
| 152 |
JSApiConsumerPause = "$JS.API.CONSUMER.PAUSE.*.*" |
| 153 |
JSApiConsumerPauseT = "$JS.API.CONSUMER.PAUSE.%s.%s" |
| 154 |
|
| 155 |
// JSApiRequestNextT is the prefix for the request next message(s) for a consumer in worker/pull mode. |
| 156 |
JSApiRequestNextT = "$JS.API.CONSUMER.MSG.NEXT.%s.%s" |
| 157 |
|
| 158 |
// JSApiConsumerResetT is the prefix for resetting a given consumer to a new starting sequence. |
| 159 |
JSApiConsumerResetT = "$JS.API.CONSUMER.RESET.%s.%s" |
| 160 |
|
| 161 |
// JSApiConsumerUnpinT is the prefix for unpinning subscription for a given consumer. |
| 162 |
JSApiConsumerUnpin = "$JS.API.CONSUMER.UNPIN.*.*" |
| 163 |
JSApiConsumerUnpinT = "$JS.API.CONSUMER.UNPIN.%s.%s" |
| 164 |
|
| 165 |
// jsRequestNextPre |
| 166 |
jsRequestNextPre = "$JS.API.CONSUMER.MSG.NEXT." |
| 167 |
|
| 168 |
// For snapshots and restores. The ack will have additional tokens. |
| 169 |
jsSnapshotAckT = "$JS.SNAPSHOT.ACK.%s.%s" |
| 170 |
jsRestoreDeliverT = "$JS.SNAPSHOT.RESTORE.%s.%s" |
| 171 |
|
| 172 |
// JSApiStreamRemovePeer is the endpoint to remove a peer from a clustered stream and its consumers. |
| 173 |
// Will return JSON response. |
| 174 |
JSApiStreamRemovePeer = "$JS.API.STREAM.PEER.REMOVE.*" |
| 175 |
JSApiStreamRemovePeerT = "$JS.API.STREAM.PEER.REMOVE.%s" |
| 176 |
|
| 177 |
// JSApiStreamLeaderStepDown is the endpoint to have stream leader stepdown. |
| 178 |
// Will return JSON response. |
| 179 |
JSApiStreamLeaderStepDown = "$JS.API.STREAM.LEADER.STEPDOWN.*" |
| 180 |
JSApiStreamLeaderStepDownT = "$JS.API.STREAM.LEADER.STEPDOWN.%s" |
| 181 |
|
| 182 |
// JSApiConsumerLeaderStepDown is the endpoint to have consumer leader stepdown. |
| 183 |
// Will return JSON response. |
| 184 |
JSApiConsumerLeaderStepDown = "$JS.API.CONSUMER.LEADER.STEPDOWN.*.*" |
| 185 |
JSApiConsumerLeaderStepDownT = "$JS.API.CONSUMER.LEADER.STEPDOWN.%s.%s" |
| 186 |
|
| 187 |
// JSApiLeaderStepDown is the endpoint to have our metaleader stepdown. |
| 188 |
// Only works from system account. |
| 189 |
// Will return JSON response. |
| 190 |
JSApiLeaderStepDown = "$JS.API.META.LEADER.STEPDOWN" |
| 191 |
|
| 192 |
// JSApiRemoveServer is the endpoint to remove a peer server from the cluster. |
| 193 |
// Only works from system account. |
| 194 |
// Will return JSON response. |
| 195 |
JSApiRemoveServer = "$JS.API.SERVER.REMOVE" |
| 196 |
|
| 197 |
// JSApiAccountPurge is the endpoint to purge the js content of an account |
| 198 |
// Only works from system account. |
| 199 |
// Will return JSON response. |
| 200 |
JSApiAccountPurge = "$JS.API.ACCOUNT.PURGE.*" |
| 201 |
JSApiAccountPurgeT = "$JS.API.ACCOUNT.PURGE.%s" |
| 202 |
|
| 203 |
// JSApiServerStreamMove is the endpoint to move streams off a server |
| 204 |
// Only works from system account. |
| 205 |
// Will return JSON response. |
| 206 |
JSApiServerStreamMove = "$JS.API.ACCOUNT.STREAM.MOVE.*.*" |
| 207 |
JSApiServerStreamMoveT = "$JS.API.ACCOUNT.STREAM.MOVE.%s.%s" |
| 208 |
|
| 209 |
// JSApiServerStreamCancelMove is the endpoint to cancel a stream move |
| 210 |
// Only works from system account. |
| 211 |
// Will return JSON response. |
| 212 |
JSApiServerStreamCancelMove = "$JS.API.ACCOUNT.STREAM.CANCEL_MOVE.*.*" |
| 213 |
JSApiServerStreamCancelMoveT = "$JS.API.ACCOUNT.STREAM.CANCEL_MOVE.%s.%s" |
| 214 |
|
| 215 |
// The prefix for system level account API. |
| 216 |
jsAPIAccountPre = "$JS.API.ACCOUNT." |
| 217 |
|
| 218 |
// jsAckT is the template for the ack message stream coming back from a consumer |
| 219 |
// when they ACK/NAK, etc a message. |
| 220 |
jsAckT = "$JS.ACK.%s.%s" |
| 221 |
jsAckTv2 = "$JS.ACK.%s.%s.%s.%s" |
| 222 |
jsAckPre = "$JS.ACK." |
| 223 |
jsAckPreLen = len(jsAckPre) |
| 224 |
|
| 225 |
// jsFlowControl is for flow control subjects. |
| 226 |
jsFlowControlPre = "$JS.FC." |
| 227 |
// jsFlowControl is for FC responses. |
| 228 |
jsFlowControl = "$JS.FC.%s.%s.*" |
| 229 |
jsFlowControlV2 = "$JS.FC.%s.%s.%s.%s.*" |
| 230 |
|
| 231 |
// JSAdvisoryPrefix is a prefix for all JetStream advisories. |
| 232 |
JSAdvisoryPrefix = "$JS.EVENT.ADVISORY" |
| 233 |
|
| 234 |
// JSMetricPrefix is a prefix for all JetStream metrics. |
| 235 |
JSMetricPrefix = "$JS.EVENT.METRIC" |
| 236 |
|
| 237 |
// JSMetricConsumerAckPre is a metric containing ack latency. |
| 238 |
JSMetricConsumerAckPre = "$JS.EVENT.METRIC.CONSUMER.ACK" |
| 239 |
|
| 240 |
// JSAdvisoryConsumerMaxDeliveryExceedPre is a notification published when a message exceeds its delivery threshold. |
| 241 |
JSAdvisoryConsumerMaxDeliveryExceedPre = "$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES" |
| 242 |
|
| 243 |
// JSAdvisoryConsumerMsgNakPre is a notification published when a message has been naked |
| 244 |
JSAdvisoryConsumerMsgNakPre = "$JS.EVENT.ADVISORY.CONSUMER.MSG_NAKED" |
| 245 |
|
| 246 |
// JSAdvisoryConsumerMsgTerminatedPre is a notification published when a message has been terminated. |
| 247 |
JSAdvisoryConsumerMsgTerminatedPre = "$JS.EVENT.ADVISORY.CONSUMER.MSG_TERMINATED" |
| 248 |
|
| 249 |
// JSAdvisoryStreamCreatedPre notification that a stream was created. |
| 250 |
JSAdvisoryStreamCreatedPre = "$JS.EVENT.ADVISORY.STREAM.CREATED" |
| 251 |
|
| 252 |
// JSAdvisoryStreamDeletedPre notification that a stream was deleted. |
| 253 |
JSAdvisoryStreamDeletedPre = "$JS.EVENT.ADVISORY.STREAM.DELETED" |
| 254 |
|
| 255 |
// JSAdvisoryStreamUpdatedPre notification that a stream was updated. |
| 256 |
JSAdvisoryStreamUpdatedPre = "$JS.EVENT.ADVISORY.STREAM.UPDATED" |
| 257 |
|
| 258 |
// JSAdvisoryConsumerCreatedPre notification that a consumer was created. |
| 259 |
JSAdvisoryConsumerCreatedPre = "$JS.EVENT.ADVISORY.CONSUMER.CREATED" |
| 260 |
|
| 261 |
// JSAdvisoryConsumerDeletedPre notification that a consumer was deleted. |
| 262 |
JSAdvisoryConsumerDeletedPre = "$JS.EVENT.ADVISORY.CONSUMER.DELETED" |
| 263 |
|
| 264 |
// JSAdvisoryConsumerPausePre notification that a consumer paused/unpaused. |
| 265 |
JSAdvisoryConsumerPausePre = "$JS.EVENT.ADVISORY.CONSUMER.PAUSE" |
| 266 |
|
| 267 |
// JSAdvisoryConsumerPinnedPre notification that a consumer was pinned. |
| 268 |
JSAdvisoryConsumerPinnedPre = "$JS.EVENT.ADVISORY.CONSUMER.PINNED" |
| 269 |
|
| 270 |
// JSAdvisoryConsumerUnpinnedPre notification that a consumer was unpinned. |
| 271 |
JSAdvisoryConsumerUnpinnedPre = "$JS.EVENT.ADVISORY.CONSUMER.UNPINNED" |
| 272 |
|
| 273 |
// JSAdvisoryStreamSnapshotCreatePre notification that a snapshot was created. |
| 274 |
JSAdvisoryStreamSnapshotCreatePre = "$JS.EVENT.ADVISORY.STREAM.SNAPSHOT_CREATE" |
| 275 |
|
| 276 |
// JSAdvisoryStreamSnapshotCompletePre notification that a snapshot was completed. |
| 277 |
JSAdvisoryStreamSnapshotCompletePre = "$JS.EVENT.ADVISORY.STREAM.SNAPSHOT_COMPLETE" |
| 278 |
|
| 279 |
// JSAdvisoryStreamRestoreCreatePre notification that a restore was start. |
| 280 |
JSAdvisoryStreamRestoreCreatePre = "$JS.EVENT.ADVISORY.STREAM.RESTORE_CREATE" |
| 281 |
|
| 282 |
// JSAdvisoryStreamRestoreCompletePre notification that a restore was completed. |
| 283 |
JSAdvisoryStreamRestoreCompletePre = "$JS.EVENT.ADVISORY.STREAM.RESTORE_COMPLETE" |
| 284 |
|
| 285 |
// JSAdvisoryDomainLeaderElectedPre notification that a jetstream domain has elected a leader. |
| 286 |
JSAdvisoryDomainLeaderElected = "$JS.EVENT.ADVISORY.DOMAIN.LEADER_ELECTED" |
| 287 |
|
| 288 |
// JSAdvisoryStreamLeaderElectedPre notification that a replicated stream has elected a leader. |
| 289 |
JSAdvisoryStreamLeaderElectedPre = "$JS.EVENT.ADVISORY.STREAM.LEADER_ELECTED" |
| 290 |
|
| 291 |
// JSAdvisoryStreamQuorumLostPre notification that a stream and its consumers are stalled. |
| 292 |
JSAdvisoryStreamQuorumLostPre = "$JS.EVENT.ADVISORY.STREAM.QUORUM_LOST" |
| 293 |
|
| 294 |
// JSAdvisoryStreamBatchAbandonedPre notification that a stream's batch was abandoned. |
| 295 |
JSAdvisoryStreamBatchAbandonedPre = "$JS.EVENT.ADVISORY.STREAM.BATCH_ABANDONED" |
| 296 |
|
| 297 |
// JSAdvisoryConsumerLeaderElectedPre notification that a replicated consumer has elected a leader. |
| 298 |
JSAdvisoryConsumerLeaderElectedPre = "$JS.EVENT.ADVISORY.CONSUMER.LEADER_ELECTED" |
| 299 |
|
| 300 |
// JSAdvisoryConsumerQuorumLostPre notification that a consumer is stalled. |
| 301 |
JSAdvisoryConsumerQuorumLostPre = "$JS.EVENT.ADVISORY.CONSUMER.QUORUM_LOST" |
| 302 |
|
| 303 |
// JSAdvisoryServerOutOfStorage notification that a server has no more storage. |
| 304 |
JSAdvisoryServerOutOfStorage = "$JS.EVENT.ADVISORY.SERVER.OUT_OF_STORAGE" |
| 305 |
|
| 306 |
// JSAdvisoryServerRemoved notification that a server has been removed from the system. |
| 307 |
JSAdvisoryServerRemoved = "$JS.EVENT.ADVISORY.SERVER.REMOVED" |
| 308 |
|
| 309 |
// JSAdvisoryAPILimitReached notification that a server has reached the JS API hard limit. |
| 310 |
JSAdvisoryAPILimitReached = "$JS.EVENT.ADVISORY.API.LIMIT_REACHED" |
| 311 |
|
| 312 |
// JSAuditAdvisory is a notification about JetStream API access. |
| 313 |
// FIXME - Add in details about who.. |
| 314 |
JSAuditAdvisory = "$JS.EVENT.ADVISORY.API" |
| 315 |
) |
| 316 |
|
| 317 |
// Headers used in $JS.API.> requests. |
| 318 |
const ( |
| 319 |
// JSRequiredApiLevel requires the API level of the responding server to have the specified minimum value. |
| 320 |
JSRequiredApiLevel = "Nats-Required-Api-Level" |
| 321 |
) |
| 322 |
|
| 323 |
var denyAllClientJs = []string{jsAllAPI, "$KV.>", "$OBJ.>"} |
| 324 |
var denyAllJs = []string{jscAllSubj, raftAllSubj, jsAllAPI, "$KV.>", "$OBJ.>"} |
| 325 |
|
| 326 |
func generateJSMappingTable(domain string) map[string]string { |
| 327 |
mappings := map[string]string{} |
| 328 |
// This set of mappings is very very very ugly. |
| 329 |
// It is a consequence of what we defined the domain prefix to be "$JS.domain.API" and it's mapping to "$JS.API" |
| 330 |
// For optics $KV and $OBJ where made to be independent subject spaces. |
| 331 |
// As materialized views of JS, they did not simply extend that subject space to say "$JS.API.KV" "$JS.API.OBJ" |
| 332 |
// This is very unfortunate!!! |
| 333 |
// Furthermore, it seemed bad to require different domain prefixes for JS/KV/OBJ. |
| 334 |
// Especially since the actual API for say KV, does use stream create from JS. |
| 335 |
// To avoid overlaps KV and OBJ views append the prefix to their API. |
| 336 |
// (Replacing $KV with the prefix allows users to create collisions with say the bucket name) |
| 337 |
// This mapping therefore needs to have extra token so that the mapping can properly discern between $JS, $KV, $OBJ |
| 338 |
for srcMappingSuffix, to := range map[string]string{ |
| 339 |
"INFO": JSApiAccountInfo, |
| 340 |
"STREAM.>": "$JS.API.STREAM.>", |
| 341 |
"CONSUMER.>": "$JS.API.CONSUMER.>", |
| 342 |
"DIRECT.>": "$JS.API.DIRECT.>", |
| 343 |
"META.>": "$JS.API.META.>", |
| 344 |
"SERVER.>": "$JS.API.SERVER.>", |
| 345 |
"ACCOUNT.>": "$JS.API.ACCOUNT.>", |
| 346 |
"$KV.>": "$KV.>", |
| 347 |
"$OBJ.>": "$OBJ.>", |
| 348 |
} { |
| 349 |
mappings[fmt.Sprintf("$JS.%s.API.%s", domain, srcMappingSuffix)] = to |
| 350 |
} |
| 351 |
return mappings |
| 352 |
} |
| 353 |
|
| 354 |
// JSMaxDescription is the maximum description length for streams and consumers. |
| 355 |
const JSMaxDescriptionLen = 4 * 1024 |
| 356 |
|
| 357 |
// JSMaxMetadataLen is the maximum length for streams and consumers metadata map. |
| 358 |
// It's calculated by summing length of all keys and values. |
| 359 |
const JSMaxMetadataLen = 128 * 1024 |
| 360 |
|
| 361 |
// JSMaxNameLen is the maximum name lengths for streams, consumers and templates. |
| 362 |
// Picked 255 as it seems to be a widely used file name limit |
| 363 |
const JSMaxNameLen = 255 |
| 364 |
|
| 365 |
// JSDefaultRequestQueueLimit is the default number of entries that we will |
| 366 |
// put on the global request queue before we react. |
| 367 |
const JSDefaultRequestQueueLimit = 10_000 |
| 368 |
|
| 369 |
// Responses for API calls. |
| 370 |
|
| 371 |
// ApiResponse is a standard response from the JetStream JSON API |
| 372 |
type ApiResponse struct { |
| 373 |
Type string `json:"type"` |
| 374 |
Error *ApiError `json:"error,omitempty"` |
| 375 |
} |
| 376 |
|
| 377 |
const JSApiSystemResponseType = "io.nats.jetstream.api.v1.system_response" |
| 378 |
|
| 379 |
// When passing back to the clients generalize store failures. |
| 380 |
var ( |
| 381 |
errStreamStoreFailed = errors.New("error creating store for stream") |
| 382 |
errConsumerStoreFailed = errors.New("error creating store for consumer") |
| 383 |
) |
| 384 |
|
| 385 |
// ToError checks if the response has a error and if it does converts it to an error avoiding |
| 386 |
// the pitfalls described by https://yourbasic.org/golang/gotcha-why-nil-error-not-equal-nil/ |
| 387 |
func (r *ApiResponse) ToError() error { |
| 388 |
if r.Error == nil { |
| 389 |
return nil |
| 390 |
} |
| 391 |
|
| 392 |
return r.Error |
| 393 |
} |
| 394 |
|
| 395 |
const JSApiOverloadedType = "io.nats.jetstream.api.v1.system_overloaded" |
| 396 |
|
| 397 |
// ApiPaged includes variables used to create paged responses from the JSON API |
| 398 |
type ApiPaged struct { |
| 399 |
Total int `json:"total"` |
| 400 |
Offset int `json:"offset"` |
| 401 |
Limit int `json:"limit"` |
| 402 |
} |
| 403 |
|
| 404 |
// ApiPagedRequest includes parameters allowing specific pages to be requests from APIs responding with ApiPaged |
| 405 |
type ApiPagedRequest struct { |
| 406 |
Offset int `json:"offset"` |
| 407 |
} |
| 408 |
|
| 409 |
// JSApiAccountInfoResponse reports back information on jetstream for this account. |
| 410 |
type JSApiAccountInfoResponse struct { |
| 411 |
ApiResponse |
| 412 |
*JetStreamAccountStats |
| 413 |
} |
| 414 |
|
| 415 |
const JSApiAccountInfoResponseType = "io.nats.jetstream.api.v1.account_info_response" |
| 416 |
|
| 417 |
// JSApiStreamCreateResponse stream creation. |
| 418 |
type JSApiStreamCreateResponse struct { |
| 419 |
ApiResponse |
| 420 |
*StreamInfo |
| 421 |
DidCreate bool `json:"did_create,omitempty"` |
| 422 |
} |
| 423 |
|
| 424 |
const JSApiStreamCreateResponseType = "io.nats.jetstream.api.v1.stream_create_response" |
| 425 |
|
| 426 |
// JSApiStreamDeleteResponse stream removal. |
| 427 |
type JSApiStreamDeleteResponse struct { |
| 428 |
ApiResponse |
| 429 |
Success bool `json:"success,omitempty"` |
| 430 |
} |
| 431 |
|
| 432 |
const JSApiStreamDeleteResponseType = "io.nats.jetstream.api.v1.stream_delete_response" |
| 433 |
|
| 434 |
// JSMaxSubjectDetails The limit of the number of subject details we will send in a stream info response. |
| 435 |
const JSMaxSubjectDetails = 100_000 |
| 436 |
|
| 437 |
type JSApiStreamInfoRequest struct { |
| 438 |
ApiPagedRequest |
| 439 |
DeletedDetails bool `json:"deleted_details,omitempty"` |
| 440 |
SubjectsFilter string `json:"subjects_filter,omitempty"` |
| 441 |
} |
| 442 |
|
| 443 |
type JSApiStreamInfoResponse struct { |
| 444 |
ApiResponse |
| 445 |
ApiPaged |
| 446 |
*StreamInfo |
| 447 |
} |
| 448 |
|
| 449 |
const JSApiStreamInfoResponseType = "io.nats.jetstream.api.v1.stream_info_response" |
| 450 |
|
| 451 |
// JSApiNamesLimit is the maximum entries we will return for streams or consumers lists. |
| 452 |
// TODO(dlc) - with header or request support could request chunked response. |
| 453 |
const JSApiNamesLimit = 1024 |
| 454 |
const JSApiListLimit = 256 |
| 455 |
|
| 456 |
type JSApiStreamNamesRequest struct { |
| 457 |
ApiPagedRequest |
| 458 |
// These are filters that can be applied to the list. |
| 459 |
Subject string `json:"subject,omitempty"` |
| 460 |
} |
| 461 |
|
| 462 |
// JSApiStreamNamesResponse list of streams. |
| 463 |
// A nil request is valid and means all streams. |
| 464 |
type JSApiStreamNamesResponse struct { |
| 465 |
ApiResponse |
| 466 |
ApiPaged |
| 467 |
Streams []string `json:"streams"` |
| 468 |
} |
| 469 |
|
| 470 |
const JSApiStreamNamesResponseType = "io.nats.jetstream.api.v1.stream_names_response" |
| 471 |
|
| 472 |
type JSApiStreamListRequest struct { |
| 473 |
ApiPagedRequest |
| 474 |
// These are filters that can be applied to the list. |
| 475 |
Subject string `json:"subject,omitempty"` |
| 476 |
} |
| 477 |
|
| 478 |
// JSApiStreamListResponse list of detailed stream information. |
| 479 |
// A nil request is valid and means all streams. |
| 480 |
type JSApiStreamListResponse struct { |
| 481 |
ApiResponse |
| 482 |
ApiPaged |
| 483 |
Streams []*StreamInfo `json:"streams"` |
| 484 |
Missing []string `json:"missing,omitempty"` |
| 485 |
Offline map[string]string `json:"offline,omitempty"` |
| 486 |
} |
| 487 |
|
| 488 |
const JSApiStreamListResponseType = "io.nats.jetstream.api.v1.stream_list_response" |
| 489 |
|
| 490 |
// JSApiStreamPurgeRequest is optional request information to the purge API. |
| 491 |
// Subject will filter the purge request to only messages that match the subject, which can have wildcards. |
| 492 |
// Sequence will purge up to but not including this sequence and can be combined with subject filtering. |
| 493 |
// Keep will specify how many messages to keep. This can also be combined with subject filtering. |
| 494 |
// Note that Sequence and Keep are mutually exclusive, so both can not be set at the same time. |
| 495 |
type JSApiStreamPurgeRequest struct { |
| 496 |
// Purge up to but not including sequence. |
| 497 |
Sequence uint64 `json:"seq,omitempty"` |
| 498 |
// Subject to match against messages for the purge command. |
| 499 |
Subject string `json:"filter,omitempty"` |
| 500 |
// Number of messages to keep. |
| 501 |
Keep uint64 `json:"keep,omitempty"` |
| 502 |
} |
| 503 |
|
| 504 |
type JSApiStreamPurgeResponse struct { |
| 505 |
ApiResponse |
| 506 |
Success bool `json:"success,omitempty"` |
| 507 |
Purged uint64 `json:"purged"` |
| 508 |
} |
| 509 |
|
| 510 |
const JSApiStreamPurgeResponseType = "io.nats.jetstream.api.v1.stream_purge_response" |
| 511 |
|
| 512 |
type JSApiConsumerUnpinRequest struct { |
| 513 |
Group string `json:"group"` |
| 514 |
} |
| 515 |
|
| 516 |
type JSApiConsumerUnpinResponse struct { |
| 517 |
ApiResponse |
| 518 |
} |
| 519 |
|
| 520 |
const JSApiConsumerUnpinResponseType = "io.nats.jetstream.api.v1.consumer_unpin_response" |
| 521 |
|
| 522 |
// JSApiStreamUpdateResponse for updating a stream. |
| 523 |
type JSApiStreamUpdateResponse struct { |
| 524 |
ApiResponse |
| 525 |
*StreamInfo |
| 526 |
} |
| 527 |
|
| 528 |
const JSApiStreamUpdateResponseType = "io.nats.jetstream.api.v1.stream_update_response" |
| 529 |
|
| 530 |
// JSApiMsgDeleteRequest delete message request. |
| 531 |
type JSApiMsgDeleteRequest struct { |
| 532 |
Seq uint64 `json:"seq"` |
| 533 |
NoErase bool `json:"no_erase,omitempty"` |
| 534 |
} |
| 535 |
|
| 536 |
type JSApiMsgDeleteResponse struct { |
| 537 |
ApiResponse |
| 538 |
Success bool `json:"success,omitempty"` |
| 539 |
} |
| 540 |
|
| 541 |
const JSApiMsgDeleteResponseType = "io.nats.jetstream.api.v1.stream_msg_delete_response" |
| 542 |
|
| 543 |
type JSApiStreamSnapshotRequest struct { |
| 544 |
// Subject to deliver the chunks to for the snapshot. |
| 545 |
DeliverSubject string `json:"deliver_subject"` |
| 546 |
// Do not include consumers in the snapshot. |
| 547 |
NoConsumers bool `json:"no_consumers,omitempty"` |
| 548 |
// Optional chunk size preference. Defaults to 128KB, |
| 549 |
// automatically clamped to within the range 1KB to 1MB. |
| 550 |
// A smaller chunk size means more in-flight messages |
| 551 |
// and more acks needed. Links with good throughput |
| 552 |
// but high latency may need to increase this. |
| 553 |
ChunkSize int `json:"chunk_size,omitempty"` |
| 554 |
// Optional window size preference. Defaults to 8MB, |
| 555 |
// automatically clamped to within the range 1KB to 32MB. |
| 556 |
// very slow connections may need to reduce this to |
| 557 |
// avoid slow consumer issues. |
| 558 |
WindowSize int `json:"window_size,omitempty"` |
| 559 |
// Check all message's checksums prior to snapshot. |
| 560 |
CheckMsgs bool `json:"jsck,omitempty"` |
| 561 |
} |
| 562 |
|
| 563 |
// JSApiStreamSnapshotResponse is the direct response to the snapshot request. |
| 564 |
type JSApiStreamSnapshotResponse struct { |
| 565 |
ApiResponse |
| 566 |
// Configuration of the given stream. |
| 567 |
Config *StreamConfig `json:"config,omitempty"` |
| 568 |
// Current State for the given stream. |
| 569 |
State *StreamState `json:"state,omitempty"` |
| 570 |
} |
| 571 |
|
| 572 |
const JSApiStreamSnapshotResponseType = "io.nats.jetstream.api.v1.stream_snapshot_response" |
| 573 |
|
| 574 |
// JSApiStreamRestoreRequest is the required restore request. |
| 575 |
type JSApiStreamRestoreRequest struct { |
| 576 |
// Configuration of the given stream. |
| 577 |
Config StreamConfig `json:"config"` |
| 578 |
// Current State for the given stream. |
| 579 |
State StreamState `json:"state"` |
| 580 |
} |
| 581 |
|
| 582 |
// JSApiStreamRestoreResponse is the direct response to the restore request. |
| 583 |
type JSApiStreamRestoreResponse struct { |
| 584 |
ApiResponse |
| 585 |
// Subject to deliver the chunks to for the snapshot restore. |
| 586 |
DeliverSubject string `json:"deliver_subject"` |
| 587 |
} |
| 588 |
|
| 589 |
const JSApiStreamRestoreResponseType = "io.nats.jetstream.api.v1.stream_restore_response" |
| 590 |
|
| 591 |
// JSApiStreamRemovePeerRequest is the required remove peer request. |
| 592 |
type JSApiStreamRemovePeerRequest struct { |
| 593 |
// Server name or peer ID of the peer to be removed. |
| 594 |
Peer string `json:"peer"` |
| 595 |
} |
| 596 |
|
| 597 |
// JSApiStreamRemovePeerResponse is the response to a remove peer request. |
| 598 |
type JSApiStreamRemovePeerResponse struct { |
| 599 |
ApiResponse |
| 600 |
Success bool `json:"success,omitempty"` |
| 601 |
} |
| 602 |
|
| 603 |
const JSApiStreamRemovePeerResponseType = "io.nats.jetstream.api.v1.stream_remove_peer_response" |
| 604 |
|
| 605 |
// JSApiStreamLeaderStepDownResponse is the response to a leader stepdown request. |
| 606 |
type JSApiStreamLeaderStepDownResponse struct { |
| 607 |
ApiResponse |
| 608 |
Success bool `json:"success,omitempty"` |
| 609 |
} |
| 610 |
|
| 611 |
const JSApiStreamLeaderStepDownResponseType = "io.nats.jetstream.api.v1.stream_leader_stepdown_response" |
| 612 |
|
| 613 |
// JSApiConsumerLeaderStepDownResponse is the response to a consumer leader stepdown request. |
| 614 |
type JSApiConsumerLeaderStepDownResponse struct { |
| 615 |
ApiResponse |
| 616 |
Success bool `json:"success,omitempty"` |
| 617 |
} |
| 618 |
|
| 619 |
const JSApiConsumerLeaderStepDownResponseType = "io.nats.jetstream.api.v1.consumer_leader_stepdown_response" |
| 620 |
|
| 621 |
// JSApiLeaderStepdownRequest allows placement control over the meta leader placement. |
| 622 |
type JSApiLeaderStepdownRequest struct { |
| 623 |
Placement *Placement `json:"placement,omitempty"` |
| 624 |
} |
| 625 |
|
| 626 |
// JSApiLeaderStepDownResponse is the response to a meta leader stepdown request. |
| 627 |
type JSApiLeaderStepDownResponse struct { |
| 628 |
ApiResponse |
| 629 |
Success bool `json:"success,omitempty"` |
| 630 |
} |
| 631 |
|
| 632 |
const JSApiLeaderStepDownResponseType = "io.nats.jetstream.api.v1.meta_leader_stepdown_response" |
| 633 |
|
| 634 |
// JSApiMetaServerRemoveRequest will remove a peer from the meta group. |
| 635 |
type JSApiMetaServerRemoveRequest struct { |
| 636 |
// Server name of the peer to be removed. |
| 637 |
Server string `json:"peer"` |
| 638 |
// Peer ID of the peer to be removed. If specified this is used |
| 639 |
// instead of the server name. |
| 640 |
Peer string `json:"peer_id,omitempty"` |
| 641 |
} |
| 642 |
|
| 643 |
// JSApiMetaServerRemoveResponse is the response to a peer removal request in the meta group. |
| 644 |
type JSApiMetaServerRemoveResponse struct { |
| 645 |
ApiResponse |
| 646 |
Success bool `json:"success,omitempty"` |
| 647 |
} |
| 648 |
|
| 649 |
const JSApiMetaServerRemoveResponseType = "io.nats.jetstream.api.v1.meta_server_remove_response" |
| 650 |
|
| 651 |
// JSApiMetaServerStreamMoveRequest will move a stream on a server to another |
| 652 |
// response to this will come as JSApiStreamUpdateResponse/JSApiStreamUpdateResponseType |
| 653 |
type JSApiMetaServerStreamMoveRequest struct { |
| 654 |
// Server name of the peer to be evacuated. |
| 655 |
Server string `json:"server,omitempty"` |
| 656 |
// Cluster the server is in |
| 657 |
Cluster string `json:"cluster,omitempty"` |
| 658 |
// Domain the sever is in |
| 659 |
Domain string `json:"domain,omitempty"` |
| 660 |
// Ephemeral placement tags for the move |
| 661 |
Tags []string `json:"tags,omitempty"` |
| 662 |
} |
| 663 |
|
| 664 |
const JSApiAccountPurgeResponseType = "io.nats.jetstream.api.v1.account_purge_response" |
| 665 |
|
| 666 |
// JSApiAccountPurgeResponse is the response to a purge request in the meta group. |
| 667 |
type JSApiAccountPurgeResponse struct { |
| 668 |
ApiResponse |
| 669 |
Initiated bool `json:"initiated,omitempty"` |
| 670 |
} |
| 671 |
|
| 672 |
// JSApiMsgGetRequest get a message request. |
| 673 |
type JSApiMsgGetRequest struct { |
| 674 |
Seq uint64 `json:"seq,omitempty"` |
| 675 |
LastFor string `json:"last_by_subj,omitempty"` |
| 676 |
NextFor string `json:"next_by_subj,omitempty"` |
| 677 |
|
| 678 |
// Batch support. Used to request more than one msg at a time. |
| 679 |
// Can be used with simple starting seq, but also NextFor with wildcards. |
| 680 |
Batch int `json:"batch,omitempty"` |
| 681 |
// This will make sure we limit how much data we blast out. If not set we will |
| 682 |
// inherit the slow consumer default max setting of the server. Default is MAX_PENDING_SIZE. |
| 683 |
MaxBytes int `json:"max_bytes,omitempty"` |
| 684 |
// Return messages as of this start time. |
| 685 |
StartTime *time.Time `json:"start_time,omitempty"` |
| 686 |
|
| 687 |
// Multiple response support. Will get the last msgs matching the subjects. These can include wildcards. |
| 688 |
MultiLastFor []string `json:"multi_last,omitempty"` |
| 689 |
// Only return messages up to this sequence. If not set, will be last sequence for the stream. |
| 690 |
UpToSeq uint64 `json:"up_to_seq,omitempty"` |
| 691 |
// Only return messages up to this time. |
| 692 |
UpToTime *time.Time `json:"up_to_time,omitempty"` |
| 693 |
// Only return the message payload, excluding headers if present. |
| 694 |
NoHeaders bool `json:"no_hdr,omitempty"` |
| 695 |
} |
| 696 |
|
| 697 |
type JSApiMsgGetResponse struct { |
| 698 |
ApiResponse |
| 699 |
Message *StoredMsg `json:"message,omitempty"` |
| 700 |
} |
| 701 |
|
| 702 |
const JSApiMsgGetResponseType = "io.nats.jetstream.api.v1.stream_msg_get_response" |
| 703 |
|
| 704 |
// JSWaitQueueDefaultMax is the default max number of outstanding requests for pull consumers. |
| 705 |
const JSWaitQueueDefaultMax = 512 |
| 706 |
|
| 707 |
type JSApiConsumerCreateResponse struct { |
| 708 |
ApiResponse |
| 709 |
*ConsumerInfo |
| 710 |
} |
| 711 |
|
| 712 |
const JSApiConsumerCreateResponseType = "io.nats.jetstream.api.v1.consumer_create_response" |
| 713 |
|
| 714 |
type JSApiConsumerDeleteResponse struct { |
| 715 |
ApiResponse |
| 716 |
Success bool `json:"success,omitempty"` |
| 717 |
} |
| 718 |
|
| 719 |
const JSApiConsumerDeleteResponseType = "io.nats.jetstream.api.v1.consumer_delete_response" |
| 720 |
|
| 721 |
type JSApiConsumerPauseRequest struct { |
| 722 |
PauseUntil time.Time `json:"pause_until,omitempty"` |
| 723 |
} |
| 724 |
|
| 725 |
const JSApiConsumerPauseResponseType = "io.nats.jetstream.api.v1.consumer_pause_response" |
| 726 |
|
| 727 |
type JSApiConsumerPauseResponse struct { |
| 728 |
ApiResponse |
| 729 |
Paused bool `json:"paused"` |
| 730 |
PauseUntil time.Time `json:"pause_until"` |
| 731 |
PauseRemaining time.Duration `json:"pause_remaining,omitempty"` |
| 732 |
} |
| 733 |
|
| 734 |
type JSApiConsumerInfoResponse struct { |
| 735 |
ApiResponse |
| 736 |
*ConsumerInfo |
| 737 |
} |
| 738 |
|
| 739 |
const JSApiConsumerInfoResponseType = "io.nats.jetstream.api.v1.consumer_info_response" |
| 740 |
|
| 741 |
type JSApiConsumersRequest struct { |
| 742 |
ApiPagedRequest |
| 743 |
} |
| 744 |
|
| 745 |
type JSApiConsumerNamesResponse struct { |
| 746 |
ApiResponse |
| 747 |
ApiPaged |
| 748 |
Consumers []string `json:"consumers"` |
| 749 |
} |
| 750 |
|
| 751 |
const JSApiConsumerNamesResponseType = "io.nats.jetstream.api.v1.consumer_names_response" |
| 752 |
|
| 753 |
type JSApiConsumerListResponse struct { |
| 754 |
ApiResponse |
| 755 |
ApiPaged |
| 756 |
Consumers []*ConsumerInfo `json:"consumers"` |
| 757 |
Missing []string `json:"missing,omitempty"` |
| 758 |
Offline map[string]string `json:"offline,omitempty"` |
| 759 |
} |
| 760 |
|
| 761 |
const JSApiConsumerListResponseType = "io.nats.jetstream.api.v1.consumer_list_response" |
| 762 |
|
| 763 |
// JSApiConsumerGetNextRequest is for getting next messages for pull based consumers. |
| 764 |
type JSApiConsumerGetNextRequest struct { |
| 765 |
Expires time.Duration `json:"expires,omitempty"` |
| 766 |
Batch int `json:"batch,omitempty"` |
| 767 |
MaxBytes int `json:"max_bytes,omitempty"` |
| 768 |
NoWait bool `json:"no_wait,omitempty"` |
| 769 |
Heartbeat time.Duration `json:"idle_heartbeat,omitempty"` |
| 770 |
PriorityGroup |
| 771 |
} |
| 772 |
|
| 773 |
// JSApiConsumerResetRequest is for resetting a consumer to a specific sequence. |
| 774 |
type JSApiConsumerResetRequest struct { |
| 775 |
Seq uint64 `json:"seq,omitempty"` |
| 776 |
} |
| 777 |
|
| 778 |
// JSApiConsumerResetResponse is a superset of JSApiConsumerCreateResponse, but including an explicit ResetSeq. |
| 779 |
type JSApiConsumerResetResponse struct { |
| 780 |
ApiResponse |
| 781 |
*ConsumerInfo |
| 782 |
ResetSeq uint64 `json:"reset_seq"` |
| 783 |
} |
| 784 |
|
| 785 |
const JSApiConsumerResetResponseType = "io.nats.jetstream.api.v1.consumer_reset_response" |
| 786 |
|
| 787 |
// Structure that holds state for a JetStream API request that is processed |
| 788 |
// in a separate long-lived go routine. This is to avoid blocking connections. |
| 789 |
type jsAPIRoutedReq struct { |
| 790 |
jsub *subscription |
| 791 |
sub *subscription |
| 792 |
acc *Account |
| 793 |
subject string |
| 794 |
reply string |
| 795 |
msg []byte |
| 796 |
pa pubArg |
| 797 |
} |
| 798 |
|
| 799 |
func (js *jetStream) apiDispatch(sub *subscription, c *client, acc *Account, subject, reply string, rmsg []byte) { |
| 800 |
// Ignore system level directives meta stepdown and peer remove requests here. |
| 801 |
if subject == JSApiLeaderStepDown || |
| 802 |
subject == JSApiRemoveServer || |
| 803 |
strings.HasPrefix(subject, jsAPIAccountPre) { |
| 804 |
return |
| 805 |
} |
| 806 |
// No lock needed, those are immutable. |
| 807 |
s, rr := js.srv, js.apiSubs.Match(subject) |
| 808 |
|
| 809 |
hdr, msg := c.msgParts(rmsg) |
| 810 |
if len(sliceHeader(ClientInfoHdr, hdr)) == 0 { |
| 811 |
// Check if this is the system account. We will let these through for the account info only. |
| 812 |
sacc := s.SystemAccount() |
| 813 |
if sacc != acc { |
| 814 |
return |
| 815 |
} |
| 816 |
if subject != JSApiAccountInfo { |
| 817 |
// Only respond from the initial server entry to the NATS system. |
| 818 |
if c.kind == CLIENT || c.kind == LEAF { |
| 819 |
var resp = ApiResponse{ |
| 820 |
Type: JSApiSystemResponseType, |
| 821 |
Error: NewJSNotEnabledForAccountError(), |
| 822 |
} |
| 823 |
s.sendAPIErrResponse(nil, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 824 |
} |
| 825 |
return |
| 826 |
} |
| 827 |
} |
| 828 |
|
| 829 |
// Short circuit for no interest. |
| 830 |
if len(rr.psubs)+len(rr.qsubs) == 0 { |
| 831 |
if (c.kind == CLIENT || c.kind == LEAF) && acc != s.SystemAccount() { |
| 832 |
ci, acc, _, _, _ := s.getRequestInfo(c, rmsg) |
| 833 |
var resp = ApiResponse{ |
| 834 |
Type: JSApiSystemResponseType, |
| 835 |
Error: NewJSBadRequestError(), |
| 836 |
} |
| 837 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 838 |
} |
| 839 |
return |
| 840 |
} |
| 841 |
|
| 842 |
// We should only have psubs and only 1 per result. |
| 843 |
if len(rr.psubs) != 1 { |
| 844 |
s.Warnf("Malformed JetStream API Request: [%s] %q", subject, rmsg) |
| 845 |
if c.kind == CLIENT || c.kind == LEAF { |
| 846 |
ci, acc, _, _, _ := s.getRequestInfo(c, rmsg) |
| 847 |
var resp = ApiResponse{ |
| 848 |
Type: JSApiSystemResponseType, |
| 849 |
Error: NewJSBadRequestError(), |
| 850 |
} |
| 851 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 852 |
} |
| 853 |
return |
| 854 |
} |
| 855 |
jsub := rr.psubs[0] |
| 856 |
|
| 857 |
// We need to make sure not to block. We will send the request to a long-lived |
| 858 |
// pool of go routines. |
| 859 |
|
| 860 |
// Increment inflight. Do this before queueing. |
| 861 |
atomic.AddInt64(&js.apiInflight, 1) |
| 862 |
|
| 863 |
// Copy the state. Note the JSAPI only uses the hdr index to piece apart the |
| 864 |
// header from the msg body. No other references are needed. |
| 865 |
// Check pending and warn if getting backed up. |
| 866 |
var queue *ipQueue[*jsAPIRoutedReq] |
| 867 |
var limit int64 |
| 868 |
if js.infoSubs.HasInterest(subject) { |
| 869 |
queue = s.jsAPIRoutedInfoReqs |
| 870 |
limit = atomic.LoadInt64(&js.infoQueueLimit) |
| 871 |
} else { |
| 872 |
queue = s.jsAPIRoutedReqs |
| 873 |
limit = atomic.LoadInt64(&js.queueLimit) |
| 874 |
} |
| 875 |
pending, _ := queue.push(&jsAPIRoutedReq{jsub, sub, acc, subject, reply, copyBytes(rmsg), c.pa}) |
| 876 |
if pending >= int(limit) { |
| 877 |
s.rateLimitFormatWarnf("%s limit reached, dropping %d requests", queue.name, pending) |
| 878 |
drained := int64(queue.drain()) |
| 879 |
atomic.AddInt64(&js.apiInflight, -drained) |
| 880 |
|
| 881 |
s.publishAdvisory(nil, JSAdvisoryAPILimitReached, JSAPILimitReachedAdvisory{ |
| 882 |
TypedEvent: TypedEvent{ |
| 883 |
Type: JSAPILimitReachedAdvisoryType, |
| 884 |
ID: nuid.Next(), |
| 885 |
Time: time.Now().UTC(), |
| 886 |
}, |
| 887 |
Server: s.Name(), |
| 888 |
Domain: js.config.Domain, |
| 889 |
Dropped: drained, |
| 890 |
}) |
| 891 |
} |
| 892 |
} |
| 893 |
|
| 894 |
func (s *Server) processJSAPIRoutedRequests() { |
| 895 |
defer s.grWG.Done() |
| 896 |
|
| 897 |
s.mu.RLock() |
| 898 |
queue, infoqueue := s.jsAPIRoutedReqs, s.jsAPIRoutedInfoReqs |
| 899 |
client := &client{srv: s, kind: JETSTREAM} |
| 900 |
s.mu.RUnlock() |
| 901 |
|
| 902 |
js := s.getJetStream() |
| 903 |
|
| 904 |
processFromQueue := func(ipq *ipQueue[*jsAPIRoutedReq]) { |
| 905 |
// Only pop one item at a time here, otherwise if the system is recovering |
| 906 |
// from queue buildup, then one worker will pull off all the tasks and the |
| 907 |
// others will be starved of work. |
| 908 |
if r, ok := ipq.popOne(); ok && r != nil { |
| 909 |
client.pa = r.pa |
| 910 |
start := time.Now() |
| 911 |
r.jsub.icb(r.sub, client, r.acc, r.subject, r.reply, r.msg) |
| 912 |
if dur := time.Since(start); dur >= readLoopReportThreshold { |
| 913 |
s.Warnf("Internal subscription on %q took too long: %v", r.subject, dur) |
| 914 |
} |
| 915 |
atomic.AddInt64(&js.apiInflight, -1) |
| 916 |
} |
| 917 |
} |
| 918 |
|
| 919 |
for { |
| 920 |
// First select case is prioritizing queue, we will only fall through |
| 921 |
// to the second select case that considers infoqueue if queue is empty. |
| 922 |
// This effectively means infos are deprioritized. |
| 923 |
select { |
| 924 |
case <-queue.ch: |
| 925 |
processFromQueue(queue) |
| 926 |
case <-s.quitCh: |
| 927 |
return |
| 928 |
default: |
| 929 |
select { |
| 930 |
case <-infoqueue.ch: |
| 931 |
processFromQueue(infoqueue) |
| 932 |
case <-queue.ch: |
| 933 |
processFromQueue(queue) |
| 934 |
case <-s.quitCh: |
| 935 |
return |
| 936 |
} |
| 937 |
} |
| 938 |
} |
| 939 |
} |
| 940 |
|
| 941 |
func (s *Server) setJetStreamExportSubs() error { |
| 942 |
js := s.getJetStream() |
| 943 |
if js == nil { |
| 944 |
return NewJSNotEnabledError() |
| 945 |
} |
| 946 |
|
| 947 |
// Start the go routine that will process API requests received by the |
| 948 |
// subscription below when they are coming from routes, etc.. |
| 949 |
const maxProcs = 16 |
| 950 |
mp := runtime.GOMAXPROCS(0) |
| 951 |
// Cap at 16 max for now on larger core setups. |
| 952 |
if mp > maxProcs { |
| 953 |
mp = maxProcs |
| 954 |
} |
| 955 |
s.jsAPIRoutedReqs = newIPQueue[*jsAPIRoutedReq](s, "JetStream API queue") |
| 956 |
s.jsAPIRoutedInfoReqs = newIPQueue[*jsAPIRoutedReq](s, "JetStream API info queue") |
| 957 |
for i := 0; i < mp; i++ { |
| 958 |
s.startGoRoutine(s.processJSAPIRoutedRequests) |
| 959 |
} |
| 960 |
|
| 961 |
// This is the catch all now for all JetStream API calls. |
| 962 |
if _, err := s.sysSubscribe(jsAllAPI, js.apiDispatch); err != nil { |
| 963 |
return err |
| 964 |
} |
| 965 |
|
| 966 |
if err := s.SystemAccount().AddServiceExport(jsAllAPI, nil); err != nil { |
| 967 |
s.Warnf("Error setting up jetstream service exports: %v", err) |
| 968 |
return err |
| 969 |
} |
| 970 |
|
| 971 |
// API handles themselves. |
| 972 |
// infopairs are deprioritized compared to pairs in processJSAPIRoutedRequests. |
| 973 |
pairs := []struct { |
| 974 |
subject string |
| 975 |
handler msgHandler |
| 976 |
}{ |
| 977 |
{JSApiStreamCreate, s.jsStreamCreateRequest}, |
| 978 |
{JSApiStreamUpdate, s.jsStreamUpdateRequest}, |
| 979 |
{JSApiStreamDelete, s.jsStreamDeleteRequest}, |
| 980 |
{JSApiStreamPurge, s.jsStreamPurgeRequest}, |
| 981 |
{JSApiStreamSnapshot, s.jsStreamSnapshotRequest}, |
| 982 |
{JSApiStreamRestore, s.jsStreamRestoreRequest}, |
| 983 |
{JSApiStreamRemovePeer, s.jsStreamRemovePeerRequest}, |
| 984 |
{JSApiStreamLeaderStepDown, s.jsStreamLeaderStepDownRequest}, |
| 985 |
{JSApiConsumerLeaderStepDown, s.jsConsumerLeaderStepDownRequest}, |
| 986 |
{JSApiMsgDelete, s.jsMsgDeleteRequest}, |
| 987 |
{JSApiMsgGet, s.jsMsgGetRequest}, |
| 988 |
{JSApiConsumerCreateEx, s.jsConsumerCreateRequest}, |
| 989 |
{JSApiConsumerCreate, s.jsConsumerCreateRequest}, |
| 990 |
{JSApiDurableCreate, s.jsConsumerCreateRequest}, |
| 991 |
{JSApiConsumerDelete, s.jsConsumerDeleteRequest}, |
| 992 |
{JSApiConsumerPause, s.jsConsumerPauseRequest}, |
| 993 |
{JSApiConsumerUnpin, s.jsConsumerUnpinRequest}, |
| 994 |
} |
| 995 |
infopairs := []struct { |
| 996 |
subject string |
| 997 |
handler msgHandler |
| 998 |
}{ |
| 999 |
{JSApiAccountInfo, s.jsAccountInfoRequest}, |
| 1000 |
{JSApiStreams, s.jsStreamNamesRequest}, |
| 1001 |
{JSApiStreamList, s.jsStreamListRequest}, |
| 1002 |
{JSApiStreamInfo, s.jsStreamInfoRequest}, |
| 1003 |
{JSApiConsumers, s.jsConsumerNamesRequest}, |
| 1004 |
{JSApiConsumerList, s.jsConsumerListRequest}, |
| 1005 |
{JSApiConsumerInfo, s.jsConsumerInfoRequest}, |
| 1006 |
} |
| 1007 |
|
| 1008 |
js.mu.Lock() |
| 1009 |
defer js.mu.Unlock() |
| 1010 |
|
| 1011 |
// As well as populating js.apiSubs for the dispatch function to use, we |
| 1012 |
// will also populate js.infoSubs, so that the dispatch function can |
| 1013 |
// decide quickly whether or not the request is an info request or not. |
| 1014 |
for _, p := range append(infopairs, pairs...) { |
| 1015 |
sub := &subscription{subject: []byte(p.subject), icb: p.handler} |
| 1016 |
if err := js.apiSubs.Insert(sub); err != nil { |
| 1017 |
return err |
| 1018 |
} |
| 1019 |
} |
| 1020 |
for _, p := range infopairs { |
| 1021 |
if err := js.infoSubs.Insert(p.subject, struct{}{}); err != nil { |
| 1022 |
return err |
| 1023 |
} |
| 1024 |
} |
| 1025 |
|
| 1026 |
return nil |
| 1027 |
} |
| 1028 |
|
| 1029 |
func (s *Server) sendAPIResponse(ci *ClientInfo, acc *Account, subject, reply, request, response string) { |
| 1030 |
acc.trackAPI() |
| 1031 |
if reply != _EMPTY_ { |
| 1032 |
s.sendInternalAccountMsg(nil, reply, response) |
| 1033 |
} |
| 1034 |
s.sendJetStreamAPIAuditAdvisory(ci, acc, subject, request, response) |
| 1035 |
} |
| 1036 |
|
| 1037 |
func (s *Server) sendAPIErrResponse(ci *ClientInfo, acc *Account, subject, reply, request, response string) { |
| 1038 |
acc.trackAPIErr() |
| 1039 |
if reply != _EMPTY_ { |
| 1040 |
s.sendInternalAccountMsg(nil, reply, response) |
| 1041 |
} |
| 1042 |
s.sendJetStreamAPIAuditAdvisory(ci, acc, subject, request, response) |
| 1043 |
} |
| 1044 |
|
| 1045 |
const errRespDelay = 500 * time.Millisecond |
| 1046 |
|
| 1047 |
type delayedAPIResponse struct { |
| 1048 |
ci *ClientInfo |
| 1049 |
acc *Account |
| 1050 |
subject string |
| 1051 |
reply string |
| 1052 |
request string |
| 1053 |
hdr []byte |
| 1054 |
response string |
| 1055 |
rg *raftGroup |
| 1056 |
deadline time.Time |
| 1057 |
noJs bool |
| 1058 |
next *delayedAPIResponse |
| 1059 |
} |
| 1060 |
|
| 1061 |
// Add `r` in the list that is maintained ordered by the `delayedAPIResponse.deadline` time. |
| 1062 |
func addDelayedResponse(head, tail **delayedAPIResponse, r *delayedAPIResponse) { |
| 1063 |
// Check if list empty. |
| 1064 |
if *head == nil { |
| 1065 |
*head, *tail = r, r |
| 1066 |
return |
| 1067 |
} |
| 1068 |
// Check if it should be added at the end, which is if after or equal to the tail. |
| 1069 |
if r.deadline.After((*tail).deadline) || r.deadline.Equal((*tail).deadline) { |
| 1070 |
(*tail).next, *tail = r, r |
| 1071 |
return |
| 1072 |
} |
| 1073 |
// Find its spot in the list. |
| 1074 |
var prev *delayedAPIResponse |
| 1075 |
for c := *head; c != nil; c = c.next { |
| 1076 |
// We insert only if we are stricly before the current `c`. |
| 1077 |
if r.deadline.Before(c.deadline) { |
| 1078 |
r.next = c |
| 1079 |
if prev != nil { |
| 1080 |
prev.next = r |
| 1081 |
} else { |
| 1082 |
*head = r |
| 1083 |
} |
| 1084 |
return |
| 1085 |
} |
| 1086 |
prev = c |
| 1087 |
} |
| 1088 |
} |
| 1089 |
|
| 1090 |
func (s *Server) delayedAPIResponder() { |
| 1091 |
defer s.grWG.Done() |
| 1092 |
var ( |
| 1093 |
head, tail *delayedAPIResponse // Linked list. |
| 1094 |
r *delayedAPIResponse // Updated by calling next(). |
| 1095 |
rqch <-chan struct{} // Quit channel of the Raft group (if present). |
| 1096 |
tm = time.NewTimer(time.Hour) |
| 1097 |
) |
| 1098 |
next := func() { |
| 1099 |
r, rqch = nil, nil |
| 1100 |
// Check that JetStream is still on. Do not exit the go routine |
| 1101 |
// since JS can be enabled/disabled. The go routine will exit |
| 1102 |
// only if server is shutdown. |
| 1103 |
js := s.getJetStream() |
| 1104 |
if js == nil { |
| 1105 |
// Reset head and tail here. Also drain the ipQueue. |
| 1106 |
head, tail = nil, nil |
| 1107 |
s.delayedAPIResponses.drain() |
| 1108 |
// Fall back into next "if" that resets timer. |
| 1109 |
} |
| 1110 |
// If there are no delayed messages then delay the timer for |
| 1111 |
// a while. |
| 1112 |
if head == nil { |
| 1113 |
tm.Reset(time.Hour) |
| 1114 |
return |
| 1115 |
} |
| 1116 |
// Get the first expected message and then reset the timer. |
| 1117 |
r = head |
| 1118 |
js.mu.RLock() |
| 1119 |
if r.rg != nil && r.rg.node != nil { |
| 1120 |
// If there's an attached Raft group to the delayed response |
| 1121 |
// then pull out the quit channel, so that we don't bother |
| 1122 |
// sending responses for entities which are now no longer |
| 1123 |
// running. |
| 1124 |
rqch = r.rg.node.QuitC() |
| 1125 |
} |
| 1126 |
js.mu.RUnlock() |
| 1127 |
tm.Reset(time.Until(r.deadline)) |
| 1128 |
} |
| 1129 |
pop := func() { |
| 1130 |
if head == nil { |
| 1131 |
return |
| 1132 |
} |
| 1133 |
head = head.next |
| 1134 |
if head == nil { |
| 1135 |
tail = nil |
| 1136 |
} |
| 1137 |
} |
| 1138 |
for { |
| 1139 |
select { |
| 1140 |
case <-s.delayedAPIResponses.ch: |
| 1141 |
v, ok := s.delayedAPIResponses.popOne() |
| 1142 |
if !ok { |
| 1143 |
continue |
| 1144 |
} |
| 1145 |
// Add it to the list, and if ends up being the head, set things up. |
| 1146 |
addDelayedResponse(&head, &tail, v) |
| 1147 |
if v == head { |
| 1148 |
next() |
| 1149 |
} |
| 1150 |
case <-s.quitCh: |
| 1151 |
return |
| 1152 |
case <-rqch: |
| 1153 |
// If we were the head, drop and setup things for next. |
| 1154 |
if r != nil && r == head { |
| 1155 |
pop() |
| 1156 |
} |
| 1157 |
next() |
| 1158 |
case <-tm.C: |
| 1159 |
if r != nil { |
| 1160 |
// If it's not a JS API error, send it as a raw response without additional API/audit tracking. |
| 1161 |
if r.noJs { |
| 1162 |
s.sendInternalAccountMsgWithReply(r.acc, r.subject, _EMPTY_, r.hdr, r.response, false) |
| 1163 |
} else { |
| 1164 |
s.sendAPIErrResponse(r.ci, r.acc, r.subject, r.reply, r.request, r.response) |
| 1165 |
} |
| 1166 |
pop() |
| 1167 |
} |
| 1168 |
next() |
| 1169 |
} |
| 1170 |
} |
| 1171 |
} |
| 1172 |
|
| 1173 |
func (s *Server) sendDelayedAPIErrResponse(ci *ClientInfo, acc *Account, subject, reply, request, response string, rg *raftGroup, duration time.Duration) { |
| 1174 |
s.delayedAPIResponses.push(&delayedAPIResponse{ |
| 1175 |
ci, acc, subject, reply, request, nil, response, rg, time.Now().Add(duration), false, nil, |
| 1176 |
}) |
| 1177 |
} |
| 1178 |
|
| 1179 |
func (s *Server) sendDelayedErrResponse(acc *Account, subject string, hdr []byte, response string, duration time.Duration) { |
| 1180 |
s.delayedAPIResponses.push(&delayedAPIResponse{ |
| 1181 |
nil, acc, subject, _EMPTY_, _EMPTY_, hdr, response, nil, time.Now().Add(duration), true, nil, |
| 1182 |
}) |
| 1183 |
} |
| 1184 |
|
| 1185 |
func (s *Server) getRequestInfo(c *client, raw []byte) (pci *ClientInfo, acc *Account, hdr, msg []byte, err error) { |
| 1186 |
hdr, msg = c.msgParts(raw) |
| 1187 |
var ci ClientInfo |
| 1188 |
|
| 1189 |
if len(hdr) > 0 { |
| 1190 |
if err := json.Unmarshal(sliceHeader(ClientInfoHdr, hdr), &ci); err != nil { |
| 1191 |
return nil, nil, nil, nil, err |
| 1192 |
} |
| 1193 |
} |
| 1194 |
|
| 1195 |
if ci.Service != _EMPTY_ { |
| 1196 |
acc, _ = s.LookupAccount(ci.Service) |
| 1197 |
} else if ci.Account != _EMPTY_ { |
| 1198 |
acc, _ = s.LookupAccount(ci.Account) |
| 1199 |
} else { |
| 1200 |
// Direct $SYS access. |
| 1201 |
acc = c.acc |
| 1202 |
if acc == nil { |
| 1203 |
acc = s.SystemAccount() |
| 1204 |
} |
| 1205 |
} |
| 1206 |
if acc == nil { |
| 1207 |
return nil, nil, nil, nil, ErrMissingAccount |
| 1208 |
} |
| 1209 |
return &ci, acc, hdr, msg, nil |
| 1210 |
} |
| 1211 |
|
| 1212 |
func (s *Server) unmarshalRequest(c *client, acc *Account, subject string, msg []byte, v any) error { |
| 1213 |
decoder := json.NewDecoder(bytes.NewReader(msg)) |
| 1214 |
decoder.DisallowUnknownFields() |
| 1215 |
|
| 1216 |
for { |
| 1217 |
if err := decoder.Decode(v); err != nil { |
| 1218 |
if err == io.EOF { |
| 1219 |
return nil |
| 1220 |
} |
| 1221 |
|
| 1222 |
var syntaxErr *json.SyntaxError |
| 1223 |
if errors.As(err, &syntaxErr) { |
| 1224 |
err = fmt.Errorf("%w at offset %d", err, syntaxErr.Offset) |
| 1225 |
} |
| 1226 |
|
| 1227 |
c.RateLimitWarnf("Invalid JetStream request '%s > %s': %s", acc, subject, err) |
| 1228 |
|
| 1229 |
if js := s.getJetStream(); js != nil && js.config.Strict { |
| 1230 |
return err |
| 1231 |
} |
| 1232 |
|
| 1233 |
return json.Unmarshal(msg, v) |
| 1234 |
} |
| 1235 |
} |
| 1236 |
} |
| 1237 |
|
| 1238 |
func (a *Account) trackAPI() { |
| 1239 |
a.mu.RLock() |
| 1240 |
jsa := a.js |
| 1241 |
a.mu.RUnlock() |
| 1242 |
if jsa != nil { |
| 1243 |
jsa.usageMu.Lock() |
| 1244 |
jsa.usageApi++ |
| 1245 |
jsa.apiTotal++ |
| 1246 |
jsa.sendClusterUsageUpdate() |
| 1247 |
atomic.AddInt64(&jsa.js.apiTotal, 1) |
| 1248 |
jsa.usageMu.Unlock() |
| 1249 |
} |
| 1250 |
} |
| 1251 |
|
| 1252 |
func (a *Account) trackAPIErr() { |
| 1253 |
a.mu.RLock() |
| 1254 |
jsa := a.js |
| 1255 |
a.mu.RUnlock() |
| 1256 |
if jsa != nil { |
| 1257 |
jsa.usageMu.Lock() |
| 1258 |
jsa.usageApi++ |
| 1259 |
jsa.apiTotal++ |
| 1260 |
jsa.usageErr++ |
| 1261 |
jsa.apiErrors++ |
| 1262 |
jsa.sendClusterUsageUpdate() |
| 1263 |
atomic.AddInt64(&jsa.js.apiTotal, 1) |
| 1264 |
atomic.AddInt64(&jsa.js.apiErrors, 1) |
| 1265 |
jsa.usageMu.Unlock() |
| 1266 |
} |
| 1267 |
} |
| 1268 |
|
| 1269 |
const badAPIRequestT = "Malformed JetStream API Request: %q" |
| 1270 |
|
| 1271 |
// Helper function to check on JetStream being enabled but also on status of leafnodes |
| 1272 |
// If the local account is not enabled but does have leafnode connectivity we will not |
| 1273 |
// want to error immediately and let the other side decide. |
| 1274 |
func (a *Account) checkJetStream() (enabled, shouldError bool) { |
| 1275 |
a.mu.RLock() |
| 1276 |
defer a.mu.RUnlock() |
| 1277 |
return a.js != nil, a.nleafs+a.nrleafs == 0 |
| 1278 |
} |
| 1279 |
|
| 1280 |
// Request for current usage and limits for this account. |
| 1281 |
func (s *Server) jsAccountInfoRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 1282 |
if c == nil || !s.JetStreamEnabled() { |
| 1283 |
return |
| 1284 |
} |
| 1285 |
|
| 1286 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 1287 |
if err != nil { |
| 1288 |
s.Warnf(badAPIRequestT, msg) |
| 1289 |
return |
| 1290 |
} |
| 1291 |
|
| 1292 |
var resp = JSApiAccountInfoResponse{ApiResponse: ApiResponse{Type: JSApiAccountInfoResponseType}} |
| 1293 |
|
| 1294 |
// Determine if we should proceed here when we are in clustered mode. |
| 1295 |
if s.JetStreamIsClustered() { |
| 1296 |
js, cc := s.getJetStreamCluster() |
| 1297 |
if js == nil || cc == nil { |
| 1298 |
return |
| 1299 |
} |
| 1300 |
if js.isLeaderless() { |
| 1301 |
resp.Error = NewJSClusterNotAvailError() |
| 1302 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1303 |
return |
| 1304 |
} |
| 1305 |
// Make sure we are meta leader. |
| 1306 |
if !s.JetStreamIsLeader() { |
| 1307 |
return |
| 1308 |
} |
| 1309 |
} |
| 1310 |
|
| 1311 |
if errorOnRequiredApiLevel(hdr) { |
| 1312 |
resp.Error = NewJSRequiredApiLevelError() |
| 1313 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1314 |
return |
| 1315 |
} |
| 1316 |
|
| 1317 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 1318 |
if !doErr { |
| 1319 |
return |
| 1320 |
} |
| 1321 |
resp.Error = NewJSNotEnabledForAccountError() |
| 1322 |
} else { |
| 1323 |
stats := acc.JetStreamUsage() |
| 1324 |
resp.JetStreamAccountStats = &stats |
| 1325 |
} |
| 1326 |
b, err := json.Marshal(resp) |
| 1327 |
if err != nil { |
| 1328 |
return |
| 1329 |
} |
| 1330 |
|
| 1331 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), string(b)) |
| 1332 |
} |
| 1333 |
|
| 1334 |
// Helpers for token extraction. |
| 1335 |
func streamNameFromSubject(subject string) string { |
| 1336 |
return tokenAt(subject, 5) |
| 1337 |
} |
| 1338 |
|
| 1339 |
func consumerNameFromSubject(subject string) string { |
| 1340 |
return tokenAt(subject, 6) |
| 1341 |
} |
| 1342 |
|
| 1343 |
func (s *Server) jsonResponse(v any) string { |
| 1344 |
b, err := json.Marshal(v) |
| 1345 |
if err != nil { |
| 1346 |
s.Warnf("Problem marshaling JSON for JetStream API:", err) |
| 1347 |
return "" |
| 1348 |
} |
| 1349 |
return string(b) |
| 1350 |
} |
| 1351 |
|
| 1352 |
// Read lock must be held |
| 1353 |
func (jsa *jsAccount) tieredReservation(tier string, cfg *StreamConfig) int64 { |
| 1354 |
var reservation int64 |
| 1355 |
for _, mset := range jsa.streams { |
| 1356 |
mset.cfgMu.RLock() |
| 1357 |
name, storage, replicas, maxBytes := mset.cfg.Name, mset.cfg.Storage, mset.cfg.Replicas, mset.cfg.MaxBytes |
| 1358 |
mset.cfgMu.RUnlock() |
| 1359 |
// Don't count the stream toward the limit if it already exists. |
| 1360 |
if name == cfg.Name { |
| 1361 |
continue |
| 1362 |
} |
| 1363 |
if (tier == _EMPTY_ || isSameTier(replicas, cfg.Replicas)) && maxBytes > 0 && storage == cfg.Storage { |
| 1364 |
reservation = addSaturate(reservation, accountReservation(tier, replicas, maxBytes)) |
| 1365 |
} |
| 1366 |
} |
| 1367 |
return reservation |
| 1368 |
} |
| 1369 |
|
| 1370 |
// Request to create a stream. |
| 1371 |
func (s *Server) jsStreamCreateRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 1372 |
if c == nil || !s.JetStreamEnabled() { |
| 1373 |
return |
| 1374 |
} |
| 1375 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 1376 |
if err != nil { |
| 1377 |
s.Warnf(badAPIRequestT, msg) |
| 1378 |
return |
| 1379 |
} |
| 1380 |
|
| 1381 |
var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}} |
| 1382 |
|
| 1383 |
// Determine if we should proceed here when we are in clustered mode. |
| 1384 |
if s.JetStreamIsClustered() { |
| 1385 |
js, cc := s.getJetStreamCluster() |
| 1386 |
if js == nil || cc == nil { |
| 1387 |
return |
| 1388 |
} |
| 1389 |
if js.isLeaderless() { |
| 1390 |
resp.Error = NewJSClusterNotAvailError() |
| 1391 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1392 |
return |
| 1393 |
} |
| 1394 |
// Make sure we are meta leader. |
| 1395 |
if !s.JetStreamIsLeader() { |
| 1396 |
return |
| 1397 |
} |
| 1398 |
} |
| 1399 |
|
| 1400 |
if errorOnRequiredApiLevel(hdr) { |
| 1401 |
resp.Error = NewJSRequiredApiLevelError() |
| 1402 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1403 |
return |
| 1404 |
} |
| 1405 |
|
| 1406 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 1407 |
if doErr { |
| 1408 |
resp.Error = NewJSNotEnabledForAccountError() |
| 1409 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1410 |
} |
| 1411 |
return |
| 1412 |
} |
| 1413 |
|
| 1414 |
var cfg StreamConfigRequest |
| 1415 |
if err := s.unmarshalRequest(c, acc, subject, msg, &cfg); err != nil { |
| 1416 |
resp.Error = NewJSInvalidJSONError(err) |
| 1417 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1418 |
return |
| 1419 |
} |
| 1420 |
|
| 1421 |
// Initialize asset version metadata. |
| 1422 |
setStaticStreamMetadata(&cfg.StreamConfig) |
| 1423 |
|
| 1424 |
streamName := streamNameFromSubject(subject) |
| 1425 |
if streamName != cfg.Name { |
| 1426 |
resp.Error = NewJSStreamMismatchError() |
| 1427 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1428 |
return |
| 1429 |
} |
| 1430 |
|
| 1431 |
// Check for path like separators in the name. |
| 1432 |
if strings.ContainsAny(streamName, `\/`) { |
| 1433 |
resp.Error = NewJSStreamNameContainsPathSeparatorsError() |
| 1434 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1435 |
return |
| 1436 |
} |
| 1437 |
|
| 1438 |
// Can't create a stream with a sealed state. |
| 1439 |
if cfg.Sealed { |
| 1440 |
resp.Error = NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration for create can not be sealed")) |
| 1441 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1442 |
return |
| 1443 |
} |
| 1444 |
|
| 1445 |
// If we are told to do mirror direct but are not mirroring, error. |
| 1446 |
if cfg.MirrorDirect && cfg.Mirror == nil { |
| 1447 |
resp.Error = NewJSStreamInvalidConfigError(fmt.Errorf("stream has no mirror but does have mirror direct")) |
| 1448 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1449 |
return |
| 1450 |
} |
| 1451 |
|
| 1452 |
// Hand off to cluster for processing. |
| 1453 |
if s.JetStreamIsClustered() { |
| 1454 |
s.jsClusteredStreamRequest(ci, acc, subject, reply, rmsg, &cfg) |
| 1455 |
return |
| 1456 |
} |
| 1457 |
|
| 1458 |
if err := acc.jsNonClusteredStreamLimitsCheck(&cfg.StreamConfig); err != nil { |
| 1459 |
resp.Error = err |
| 1460 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1461 |
return |
| 1462 |
} |
| 1463 |
|
| 1464 |
mset, err := acc.addStreamPedantic(&cfg.StreamConfig, cfg.Pedantic) |
| 1465 |
if err != nil { |
| 1466 |
if IsNatsErr(err, JSStreamStoreFailedF) { |
| 1467 |
s.Warnf("Stream create failed for '%s > %s': %v", acc, streamName, err) |
| 1468 |
err = errStreamStoreFailed |
| 1469 |
} |
| 1470 |
resp.Error = NewJSStreamCreateError(err, Unless(err)) |
| 1471 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1472 |
return |
| 1473 |
} |
| 1474 |
msetCfg := mset.config() |
| 1475 |
resp.StreamInfo = &StreamInfo{ |
| 1476 |
Created: mset.createdTime(), |
| 1477 |
State: mset.state(), |
| 1478 |
Config: *setDynamicStreamMetadata(&msetCfg), |
| 1479 |
TimeStamp: time.Now().UTC(), |
| 1480 |
Mirror: mset.mirrorInfo(), |
| 1481 |
Sources: mset.sourcesInfo(), |
| 1482 |
} |
| 1483 |
resp.DidCreate = true |
| 1484 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 1485 |
} |
| 1486 |
|
| 1487 |
// Request to update a stream. |
| 1488 |
func (s *Server) jsStreamUpdateRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 1489 |
if c == nil || !s.JetStreamEnabled() { |
| 1490 |
return |
| 1491 |
} |
| 1492 |
|
| 1493 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 1494 |
if err != nil { |
| 1495 |
s.Warnf(badAPIRequestT, msg) |
| 1496 |
return |
| 1497 |
} |
| 1498 |
|
| 1499 |
var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}} |
| 1500 |
|
| 1501 |
// Determine if we should proceed here when we are in clustered mode. |
| 1502 |
if s.JetStreamIsClustered() { |
| 1503 |
js, cc := s.getJetStreamCluster() |
| 1504 |
if js == nil || cc == nil { |
| 1505 |
return |
| 1506 |
} |
| 1507 |
if js.isLeaderless() { |
| 1508 |
resp.Error = NewJSClusterNotAvailError() |
| 1509 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1510 |
return |
| 1511 |
} |
| 1512 |
// Make sure we are meta leader. |
| 1513 |
if !s.JetStreamIsLeader() { |
| 1514 |
return |
| 1515 |
} |
| 1516 |
} |
| 1517 |
|
| 1518 |
if errorOnRequiredApiLevel(hdr) { |
| 1519 |
resp.Error = NewJSRequiredApiLevelError() |
| 1520 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1521 |
return |
| 1522 |
} |
| 1523 |
|
| 1524 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 1525 |
if doErr { |
| 1526 |
resp.Error = NewJSNotEnabledForAccountError() |
| 1527 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1528 |
} |
| 1529 |
return |
| 1530 |
} |
| 1531 |
var ncfg StreamConfigRequest |
| 1532 |
if err := s.unmarshalRequest(c, acc, subject, msg, &ncfg); err != nil { |
| 1533 |
resp.Error = NewJSInvalidJSONError(err) |
| 1534 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1535 |
return |
| 1536 |
} |
| 1537 |
|
| 1538 |
cfg, apiErr := s.checkStreamCfg(&ncfg.StreamConfig, acc, ncfg.Pedantic) |
| 1539 |
if apiErr != nil { |
| 1540 |
resp.Error = apiErr |
| 1541 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1542 |
return |
| 1543 |
} |
| 1544 |
|
| 1545 |
streamName := streamNameFromSubject(subject) |
| 1546 |
if streamName != cfg.Name { |
| 1547 |
resp.Error = NewJSStreamMismatchError() |
| 1548 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1549 |
return |
| 1550 |
} |
| 1551 |
|
| 1552 |
// Handle clustered version here. |
| 1553 |
if s.JetStreamIsClustered() { |
| 1554 |
s.jsClusteredStreamUpdateRequest(ci, acc, subject, reply, copyBytes(rmsg), &cfg, nil, ncfg.Pedantic) |
| 1555 |
return |
| 1556 |
} |
| 1557 |
|
| 1558 |
mset, err := acc.lookupStream(streamName) |
| 1559 |
if err != nil { |
| 1560 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 1561 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1562 |
return |
| 1563 |
} |
| 1564 |
if mset.offlineReason != _EMPTY_ { |
| 1565 |
resp.Error = NewJSStreamOfflineReasonError(errors.New(mset.offlineReason)) |
| 1566 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 1567 |
return |
| 1568 |
} |
| 1569 |
|
| 1570 |
// Update asset version metadata. |
| 1571 |
setStaticStreamMetadata(&cfg) |
| 1572 |
|
| 1573 |
if err := mset.updatePedantic(&cfg, ncfg.Pedantic); err != nil { |
| 1574 |
resp.Error = NewJSStreamUpdateError(err, Unless(err)) |
| 1575 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1576 |
return |
| 1577 |
} |
| 1578 |
|
| 1579 |
msetCfg := mset.config() |
| 1580 |
resp.StreamInfo = &StreamInfo{ |
| 1581 |
Created: mset.createdTime(), |
| 1582 |
State: mset.state(), |
| 1583 |
Config: *setDynamicStreamMetadata(&msetCfg), |
| 1584 |
Domain: s.getOpts().JetStreamDomain, |
| 1585 |
Mirror: mset.mirrorInfo(), |
| 1586 |
Sources: mset.sourcesInfo(), |
| 1587 |
TimeStamp: time.Now().UTC(), |
| 1588 |
} |
| 1589 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 1590 |
} |
| 1591 |
|
| 1592 |
// Request for the list of all stream names. |
| 1593 |
func (s *Server) jsStreamNamesRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 1594 |
if c == nil || !s.JetStreamEnabled() { |
| 1595 |
return |
| 1596 |
} |
| 1597 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 1598 |
if err != nil { |
| 1599 |
s.Warnf(badAPIRequestT, msg) |
| 1600 |
return |
| 1601 |
} |
| 1602 |
|
| 1603 |
var resp = JSApiStreamNamesResponse{ApiResponse: ApiResponse{Type: JSApiStreamNamesResponseType}} |
| 1604 |
|
| 1605 |
// Determine if we should proceed here when we are in clustered mode. |
| 1606 |
if s.JetStreamIsClustered() { |
| 1607 |
js, cc := s.getJetStreamCluster() |
| 1608 |
if js == nil || cc == nil { |
| 1609 |
return |
| 1610 |
} |
| 1611 |
if js.isLeaderless() { |
| 1612 |
resp.Error = NewJSClusterNotAvailError() |
| 1613 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1614 |
return |
| 1615 |
} |
| 1616 |
// Make sure we are meta leader. |
| 1617 |
if !s.JetStreamIsLeader() { |
| 1618 |
return |
| 1619 |
} |
| 1620 |
} |
| 1621 |
|
| 1622 |
if errorOnRequiredApiLevel(hdr) { |
| 1623 |
resp.Error = NewJSRequiredApiLevelError() |
| 1624 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1625 |
return |
| 1626 |
} |
| 1627 |
|
| 1628 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 1629 |
if doErr { |
| 1630 |
resp.Error = NewJSNotEnabledForAccountError() |
| 1631 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1632 |
} |
| 1633 |
return |
| 1634 |
} |
| 1635 |
|
| 1636 |
var offset int |
| 1637 |
var filter string |
| 1638 |
|
| 1639 |
if isJSONObjectOrArray(msg) { |
| 1640 |
var req JSApiStreamNamesRequest |
| 1641 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 1642 |
resp.Error = NewJSInvalidJSONError(err) |
| 1643 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1644 |
return |
| 1645 |
} |
| 1646 |
offset = max(req.Offset, 0) |
| 1647 |
if req.Subject != _EMPTY_ { |
| 1648 |
filter = req.Subject |
| 1649 |
} |
| 1650 |
} |
| 1651 |
|
| 1652 |
// TODO(dlc) - Maybe hold these results for large results that we expect to be paged. |
| 1653 |
// TODO(dlc) - If this list is long maybe do this in a Go routine? |
| 1654 |
var numStreams int |
| 1655 |
if s.JetStreamIsClustered() { |
| 1656 |
js, cc := s.getJetStreamCluster() |
| 1657 |
if js == nil || cc == nil { |
| 1658 |
// TODO(dlc) - Debug or Warn? |
| 1659 |
return |
| 1660 |
} |
| 1661 |
js.mu.RLock() |
| 1662 |
for stream, sa := range cc.streams[acc.Name] { |
| 1663 |
if IsNatsErr(sa.err, JSClusterNotAssignedErr) { |
| 1664 |
continue |
| 1665 |
} |
| 1666 |
if filter != _EMPTY_ { |
| 1667 |
// These could not have subjects auto-filled in since they are raw and unprocessed. |
| 1668 |
if len(sa.Config.Subjects) == 0 { |
| 1669 |
if SubjectsCollide(filter, sa.Config.Name) { |
| 1670 |
resp.Streams = append(resp.Streams, stream) |
| 1671 |
} |
| 1672 |
} else { |
| 1673 |
for _, subj := range sa.Config.Subjects { |
| 1674 |
if SubjectsCollide(filter, subj) { |
| 1675 |
resp.Streams = append(resp.Streams, stream) |
| 1676 |
break |
| 1677 |
} |
| 1678 |
} |
| 1679 |
} |
| 1680 |
} else { |
| 1681 |
resp.Streams = append(resp.Streams, stream) |
| 1682 |
} |
| 1683 |
} |
| 1684 |
js.mu.RUnlock() |
| 1685 |
if len(resp.Streams) > 1 { |
| 1686 |
slices.Sort(resp.Streams) |
| 1687 |
} |
| 1688 |
numStreams = len(resp.Streams) |
| 1689 |
if offset > numStreams { |
| 1690 |
offset = numStreams |
| 1691 |
} |
| 1692 |
if offset > 0 { |
| 1693 |
resp.Streams = resp.Streams[offset:] |
| 1694 |
} |
| 1695 |
if len(resp.Streams) > JSApiNamesLimit { |
| 1696 |
resp.Streams = resp.Streams[:JSApiNamesLimit] |
| 1697 |
} |
| 1698 |
} else { |
| 1699 |
// Snapshot names once to avoid repeated cfgMu RLocks during sort+append. |
| 1700 |
msets := acc.filteredStreams(filter) |
| 1701 |
names := make([]string, len(msets)) |
| 1702 |
for i, mset := range msets { |
| 1703 |
names[i] = mset.getCfgName() |
| 1704 |
} |
| 1705 |
if len(names) > 1 { |
| 1706 |
slices.Sort(names) |
| 1707 |
} |
| 1708 |
|
| 1709 |
numStreams = len(names) |
| 1710 |
if offset > numStreams { |
| 1711 |
offset = numStreams |
| 1712 |
} |
| 1713 |
|
| 1714 |
for _, name := range names[offset:] { |
| 1715 |
resp.Streams = append(resp.Streams, name) |
| 1716 |
if len(resp.Streams) >= JSApiNamesLimit { |
| 1717 |
break |
| 1718 |
} |
| 1719 |
} |
| 1720 |
} |
| 1721 |
resp.Total = numStreams |
| 1722 |
resp.Limit = JSApiNamesLimit |
| 1723 |
resp.Offset = offset |
| 1724 |
|
| 1725 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 1726 |
} |
| 1727 |
|
| 1728 |
// Request for the list of all detailed stream info. |
| 1729 |
// TODO(dlc) - combine with above long term |
| 1730 |
func (s *Server) jsStreamListRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 1731 |
if c == nil || !s.JetStreamEnabled() { |
| 1732 |
return |
| 1733 |
} |
| 1734 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 1735 |
if err != nil { |
| 1736 |
s.Warnf(badAPIRequestT, msg) |
| 1737 |
return |
| 1738 |
} |
| 1739 |
|
| 1740 |
var resp = JSApiStreamListResponse{ |
| 1741 |
ApiResponse: ApiResponse{Type: JSApiStreamListResponseType}, |
| 1742 |
Streams: []*StreamInfo{}, |
| 1743 |
} |
| 1744 |
|
| 1745 |
// Determine if we should proceed here when we are in clustered mode. |
| 1746 |
if s.JetStreamIsClustered() { |
| 1747 |
js, cc := s.getJetStreamCluster() |
| 1748 |
if js == nil || cc == nil { |
| 1749 |
return |
| 1750 |
} |
| 1751 |
if js.isLeaderless() { |
| 1752 |
resp.Error = NewJSClusterNotAvailError() |
| 1753 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1754 |
return |
| 1755 |
} |
| 1756 |
// Make sure we are meta leader. |
| 1757 |
if !s.JetStreamIsLeader() { |
| 1758 |
return |
| 1759 |
} |
| 1760 |
} |
| 1761 |
|
| 1762 |
if errorOnRequiredApiLevel(hdr) { |
| 1763 |
resp.Error = NewJSRequiredApiLevelError() |
| 1764 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1765 |
return |
| 1766 |
} |
| 1767 |
|
| 1768 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 1769 |
if doErr { |
| 1770 |
resp.Error = NewJSNotEnabledForAccountError() |
| 1771 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1772 |
} |
| 1773 |
return |
| 1774 |
} |
| 1775 |
|
| 1776 |
var offset int |
| 1777 |
var filter string |
| 1778 |
|
| 1779 |
if isJSONObjectOrArray(msg) { |
| 1780 |
var req JSApiStreamListRequest |
| 1781 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 1782 |
resp.Error = NewJSInvalidJSONError(err) |
| 1783 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1784 |
return |
| 1785 |
} |
| 1786 |
offset = max(req.Offset, 0) |
| 1787 |
if req.Subject != _EMPTY_ { |
| 1788 |
filter = req.Subject |
| 1789 |
} |
| 1790 |
} |
| 1791 |
|
| 1792 |
// Clustered mode will invoke a scatter and gather. |
| 1793 |
if s.JetStreamIsClustered() { |
| 1794 |
// Need to copy these off before sending.. don't move this inside startGoRoutine!!! |
| 1795 |
msg = copyBytes(msg) |
| 1796 |
s.startGoRoutine(func() { s.jsClusteredStreamListRequest(acc, ci, filter, offset, subject, reply, msg) }) |
| 1797 |
return |
| 1798 |
} |
| 1799 |
|
| 1800 |
// TODO(dlc) - Maybe hold these results for large results that we expect to be paged. |
| 1801 |
// TODO(dlc) - If this list is long maybe do this in a Go routine? |
| 1802 |
var msets []*stream |
| 1803 |
if filter == _EMPTY_ { |
| 1804 |
msets = acc.streams() |
| 1805 |
} else { |
| 1806 |
msets = acc.filteredStreams(filter) |
| 1807 |
} |
| 1808 |
|
| 1809 |
// Snapshot names once and sort the parallel slice to avoid repeated cfgMu RLocks. |
| 1810 |
type msetWithName struct { |
| 1811 |
mset *stream |
| 1812 |
name string |
| 1813 |
} |
| 1814 |
named := make([]msetWithName, len(msets)) |
| 1815 |
for i, mset := range msets { |
| 1816 |
named[i] = msetWithName{mset, mset.getCfgName()} |
| 1817 |
} |
| 1818 |
slices.SortFunc(named, func(a, b msetWithName) int { return cmp.Compare(a.name, b.name) }) |
| 1819 |
|
| 1820 |
scnt := len(named) |
| 1821 |
if offset > scnt { |
| 1822 |
offset = scnt |
| 1823 |
} |
| 1824 |
|
| 1825 |
var missingNames []string |
| 1826 |
for _, n := range named[offset:] { |
| 1827 |
mset, name := n.mset, n.name |
| 1828 |
if mset.offlineReason != _EMPTY_ { |
| 1829 |
if resp.Offline == nil { |
| 1830 |
resp.Offline = make(map[string]string, 1) |
| 1831 |
} |
| 1832 |
resp.Offline[name] = mset.offlineReason |
| 1833 |
missingNames = append(missingNames, name) |
| 1834 |
continue |
| 1835 |
} |
| 1836 |
|
| 1837 |
config := mset.config() |
| 1838 |
resp.Streams = append(resp.Streams, &StreamInfo{ |
| 1839 |
Created: mset.createdTime(), |
| 1840 |
State: mset.state(), |
| 1841 |
Config: config, |
| 1842 |
Domain: s.getOpts().JetStreamDomain, |
| 1843 |
Mirror: mset.mirrorInfo(), |
| 1844 |
Sources: mset.sourcesInfo(), |
| 1845 |
TimeStamp: time.Now().UTC(), |
| 1846 |
}) |
| 1847 |
if len(resp.Streams) >= JSApiListLimit { |
| 1848 |
break |
| 1849 |
} |
| 1850 |
} |
| 1851 |
resp.Total = scnt |
| 1852 |
resp.Limit = JSApiListLimit |
| 1853 |
resp.Offset = offset |
| 1854 |
resp.Missing = missingNames |
| 1855 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 1856 |
} |
| 1857 |
|
| 1858 |
// Request for information about a stream. |
| 1859 |
func (s *Server) jsStreamInfoRequest(sub *subscription, c *client, a *Account, subject, reply string, rmsg []byte) { |
| 1860 |
if c == nil || !s.JetStreamEnabled() { |
| 1861 |
return |
| 1862 |
} |
| 1863 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 1864 |
if err != nil { |
| 1865 |
s.Warnf(badAPIRequestT, msg) |
| 1866 |
return |
| 1867 |
} |
| 1868 |
|
| 1869 |
streamName := streamNameFromSubject(subject) |
| 1870 |
|
| 1871 |
var resp = JSApiStreamInfoResponse{ApiResponse: ApiResponse{Type: JSApiStreamInfoResponseType}} |
| 1872 |
|
| 1873 |
// If someone creates a duplicate stream that is identical we will get this request forwarded to us. |
| 1874 |
// Make sure the response type is for a create call. |
| 1875 |
if rt := getHeader(JSResponseType, hdr); len(rt) > 0 && string(rt) == jsCreateResponse { |
| 1876 |
resp.ApiResponse.Type = JSApiStreamCreateResponseType |
| 1877 |
} |
| 1878 |
|
| 1879 |
var clusterWideConsCount int |
| 1880 |
|
| 1881 |
js, cc := s.getJetStreamCluster() |
| 1882 |
if js == nil { |
| 1883 |
return |
| 1884 |
} |
| 1885 |
// If we are in clustered mode we need to be the stream leader to proceed. |
| 1886 |
if cc != nil { |
| 1887 |
// Check to make sure the stream is assigned. |
| 1888 |
js.mu.RLock() |
| 1889 |
isLeader, sa := cc.isLeader(), js.streamAssignmentOrInflight(acc.Name, streamName) |
| 1890 |
var offline bool |
| 1891 |
if sa != nil { |
| 1892 |
clusterWideConsCount = len(sa.consumers) |
| 1893 |
offline = s.allPeersOffline(sa.Group) |
| 1894 |
if sa.unsupported != nil && sa.Group != nil && cc.meta != nil && sa.Group.isMember(cc.meta.ID()) { |
| 1895 |
// If we're a member for this stream, and it's not supported, report it as offline. |
| 1896 |
resp.Error = NewJSStreamOfflineReasonError(errors.New(sa.unsupported.reason)) |
| 1897 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 1898 |
js.mu.RUnlock() |
| 1899 |
return |
| 1900 |
} |
| 1901 |
} |
| 1902 |
js.mu.RUnlock() |
| 1903 |
|
| 1904 |
if isLeader && sa == nil { |
| 1905 |
// We can't find the stream, so mimic what would be the errors below. |
| 1906 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 1907 |
if doErr { |
| 1908 |
resp.Error = NewJSNotEnabledForAccountError() |
| 1909 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1910 |
} |
| 1911 |
return |
| 1912 |
} |
| 1913 |
// No stream present. |
| 1914 |
resp.Error = NewJSStreamNotFoundError() |
| 1915 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1916 |
return |
| 1917 |
} else if sa == nil { |
| 1918 |
if js.isLeaderless() { |
| 1919 |
resp.Error = NewJSClusterNotAvailError() |
| 1920 |
// Delaying an error response gives the leader a chance to respond before us |
| 1921 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 1922 |
} |
| 1923 |
return |
| 1924 |
} else if isLeader && offline { |
| 1925 |
resp.Error = NewJSStreamOfflineError() |
| 1926 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 1927 |
return |
| 1928 |
} |
| 1929 |
|
| 1930 |
// Check to see if we are a member of the group and if the group has no leader. |
| 1931 |
isLeaderless := js.isGroupLeaderless(sa.Group) |
| 1932 |
|
| 1933 |
// We have the stream assigned and a leader, so only the stream leader should answer. |
| 1934 |
if !acc.JetStreamIsStreamLeader(streamName) && !isLeaderless { |
| 1935 |
if js.isLeaderless() { |
| 1936 |
resp.Error = NewJSClusterNotAvailError() |
| 1937 |
// Delaying an error response gives the leader a chance to respond before us |
| 1938 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), sa.Group, errRespDelay) |
| 1939 |
return |
| 1940 |
} |
| 1941 |
|
| 1942 |
// We may be in process of electing a leader, but if this is a scale up from 1 we will still be the state leader |
| 1943 |
// while the new members work through the election and catchup process. |
| 1944 |
// Double check for that instead of exiting here and being silent. e.g. nats stream update test --replicas=3 |
| 1945 |
js.mu.RLock() |
| 1946 |
rg := sa.Group |
| 1947 |
var ourID string |
| 1948 |
if cc.meta != nil { |
| 1949 |
ourID = cc.meta.ID() |
| 1950 |
} |
| 1951 |
// We have seen cases where rg is nil at this point, |
| 1952 |
// so check explicitly and bail if that is the case. |
| 1953 |
bail := rg == nil || !rg.isMember(ourID) |
| 1954 |
if !bail { |
| 1955 |
// We know we are a member here, if this group is new and we are preferred allow us to answer. |
| 1956 |
// Also, we have seen cases where rg.node is nil at this point, |
| 1957 |
// so check explicitly and bail if that is the case. |
| 1958 |
bail = rg.Preferred != ourID || (rg.node != nil && time.Since(rg.node.Created()) > lostQuorumIntervalDefault) |
| 1959 |
} |
| 1960 |
js.mu.RUnlock() |
| 1961 |
if bail { |
| 1962 |
return |
| 1963 |
} |
| 1964 |
} |
| 1965 |
} |
| 1966 |
|
| 1967 |
if errorOnRequiredApiLevel(hdr) { |
| 1968 |
resp.Error = NewJSRequiredApiLevelError() |
| 1969 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1970 |
return |
| 1971 |
} |
| 1972 |
|
| 1973 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 1974 |
if doErr { |
| 1975 |
resp.Error = NewJSNotEnabledForAccountError() |
| 1976 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1977 |
} |
| 1978 |
return |
| 1979 |
} |
| 1980 |
|
| 1981 |
var details bool |
| 1982 |
var subjects string |
| 1983 |
var offset int |
| 1984 |
if isJSONObjectOrArray(msg) { |
| 1985 |
var req JSApiStreamInfoRequest |
| 1986 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 1987 |
resp.Error = NewJSInvalidJSONError(err) |
| 1988 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 1989 |
return |
| 1990 |
} |
| 1991 |
details, subjects = req.DeletedDetails, req.SubjectsFilter |
| 1992 |
offset = max(req.Offset, 0) |
| 1993 |
} |
| 1994 |
|
| 1995 |
mset, err := acc.lookupStream(streamName) |
| 1996 |
// Error is not to be expected at this point, but could happen if same stream trying to be created. |
| 1997 |
if err != nil { |
| 1998 |
if cc != nil { |
| 1999 |
// This could be inflight, pause for a short bit and try again. |
| 2000 |
// This will not be inline, so ok. |
| 2001 |
time.Sleep(10 * time.Millisecond) |
| 2002 |
mset, err = acc.lookupStream(streamName) |
| 2003 |
} |
| 2004 |
// Check again. |
| 2005 |
if err != nil { |
| 2006 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 2007 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2008 |
return |
| 2009 |
} |
| 2010 |
} |
| 2011 |
|
| 2012 |
if mset.offlineReason != _EMPTY_ { |
| 2013 |
resp.Error = NewJSStreamOfflineReasonError(errors.New(mset.offlineReason)) |
| 2014 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 2015 |
return |
| 2016 |
} |
| 2017 |
|
| 2018 |
config := mset.config() |
| 2019 |
resp.StreamInfo = &StreamInfo{ |
| 2020 |
Created: mset.createdTime(), |
| 2021 |
State: mset.stateWithDetail(details), |
| 2022 |
Config: *setDynamicStreamMetadata(&config), |
| 2023 |
Domain: s.getOpts().JetStreamDomain, |
| 2024 |
Cluster: js.clusterInfo(mset.raftGroup()), |
| 2025 |
Mirror: mset.mirrorInfo(), |
| 2026 |
Sources: mset.sourcesInfo(), |
| 2027 |
Alternates: js.streamAlternates(ci, config.Name), |
| 2028 |
TimeStamp: time.Now().UTC(), |
| 2029 |
} |
| 2030 |
if clusterWideConsCount > 0 { |
| 2031 |
resp.StreamInfo.State.Consumers = clusterWideConsCount |
| 2032 |
} |
| 2033 |
|
| 2034 |
// Check if they have asked for subject details. |
| 2035 |
if subjects != _EMPTY_ { |
| 2036 |
st := mset.store.SubjectsTotals(subjects) |
| 2037 |
if lst := len(st); lst > 0 { |
| 2038 |
// Common for both cases. |
| 2039 |
resp.Offset = offset |
| 2040 |
resp.Limit = JSMaxSubjectDetails |
| 2041 |
resp.Total = lst |
| 2042 |
|
| 2043 |
if offset == 0 && lst <= JSMaxSubjectDetails { |
| 2044 |
resp.StreamInfo.State.Subjects = st |
| 2045 |
} else { |
| 2046 |
// Here we have to filter list due to offset or maximum constraints. |
| 2047 |
subjs := make([]string, 0, len(st)) |
| 2048 |
for subj := range st { |
| 2049 |
subjs = append(subjs, subj) |
| 2050 |
} |
| 2051 |
// Sort it |
| 2052 |
slices.Sort(subjs) |
| 2053 |
|
| 2054 |
if offset > len(subjs) { |
| 2055 |
offset = len(subjs) |
| 2056 |
} |
| 2057 |
|
| 2058 |
end := offset + JSMaxSubjectDetails |
| 2059 |
if end > len(subjs) { |
| 2060 |
end = len(subjs) |
| 2061 |
} |
| 2062 |
actualSize := end - offset |
| 2063 |
var sd map[string]uint64 |
| 2064 |
|
| 2065 |
if actualSize > 0 { |
| 2066 |
sd = make(map[string]uint64, actualSize) |
| 2067 |
for _, ss := range subjs[offset:end] { |
| 2068 |
sd[ss] = st[ss] |
| 2069 |
} |
| 2070 |
} |
| 2071 |
resp.StreamInfo.State.Subjects = sd |
| 2072 |
} |
| 2073 |
} |
| 2074 |
} |
| 2075 |
// Check for out of band catchups. |
| 2076 |
if mset.hasCatchupPeers() { |
| 2077 |
mset.checkClusterInfo(resp.StreamInfo.Cluster) |
| 2078 |
} |
| 2079 |
|
| 2080 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 2081 |
} |
| 2082 |
|
| 2083 |
// Request to have a stream leader stepdown. |
| 2084 |
func (s *Server) jsStreamLeaderStepDownRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 2085 |
if c == nil || !s.JetStreamEnabled() { |
| 2086 |
return |
| 2087 |
} |
| 2088 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 2089 |
if err != nil { |
| 2090 |
s.Warnf(badAPIRequestT, msg) |
| 2091 |
return |
| 2092 |
} |
| 2093 |
|
| 2094 |
// Have extra token for this one. |
| 2095 |
name := tokenAt(subject, 6) |
| 2096 |
|
| 2097 |
var resp = JSApiStreamLeaderStepDownResponse{ApiResponse: ApiResponse{Type: JSApiStreamLeaderStepDownResponseType}} |
| 2098 |
|
| 2099 |
// If we are not in clustered mode this is a failed request. |
| 2100 |
if !s.JetStreamIsClustered() { |
| 2101 |
resp.Error = NewJSClusterRequiredError() |
| 2102 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2103 |
return |
| 2104 |
} |
| 2105 |
|
| 2106 |
// If we are here we are clustered. See if we are the stream leader in order to proceed. |
| 2107 |
js, cc := s.getJetStreamCluster() |
| 2108 |
if js == nil || cc == nil { |
| 2109 |
return |
| 2110 |
} |
| 2111 |
if js.isLeaderless() { |
| 2112 |
resp.Error = NewJSClusterNotAvailError() |
| 2113 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2114 |
return |
| 2115 |
} |
| 2116 |
|
| 2117 |
js.mu.RLock() |
| 2118 |
isLeader, sa := cc.isLeader(), js.streamAssignmentOrInflight(acc.Name, name) |
| 2119 |
js.mu.RUnlock() |
| 2120 |
|
| 2121 |
if isLeader && sa == nil { |
| 2122 |
resp.Error = NewJSStreamNotFoundError() |
| 2123 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2124 |
return |
| 2125 |
} else if sa == nil { |
| 2126 |
return |
| 2127 |
} |
| 2128 |
|
| 2129 |
if errorOnRequiredApiLevel(hdr) { |
| 2130 |
resp.Error = NewJSRequiredApiLevelError() |
| 2131 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2132 |
return |
| 2133 |
} |
| 2134 |
|
| 2135 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 2136 |
if doErr { |
| 2137 |
resp.Error = NewJSNotEnabledForAccountError() |
| 2138 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2139 |
} |
| 2140 |
return |
| 2141 |
} |
| 2142 |
|
| 2143 |
// Check to see if we are a member of the group and if the group has no leader. |
| 2144 |
if js.isGroupLeaderless(sa.Group) { |
| 2145 |
resp.Error = NewJSClusterNotAvailError() |
| 2146 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2147 |
return |
| 2148 |
} |
| 2149 |
|
| 2150 |
// We have the stream assigned and a leader, so only the stream leader should answer. |
| 2151 |
if !acc.JetStreamIsStreamLeader(name) { |
| 2152 |
return |
| 2153 |
} |
| 2154 |
|
| 2155 |
mset, err := acc.lookupStream(name) |
| 2156 |
if err != nil { |
| 2157 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 2158 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2159 |
return |
| 2160 |
} |
| 2161 |
|
| 2162 |
if mset == nil { |
| 2163 |
resp.Success = true |
| 2164 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 2165 |
return |
| 2166 |
} |
| 2167 |
|
| 2168 |
node := mset.raftNode() |
| 2169 |
if node == nil { |
| 2170 |
resp.Success = true |
| 2171 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 2172 |
return |
| 2173 |
} |
| 2174 |
|
| 2175 |
var preferredLeader string |
| 2176 |
if isJSONObjectOrArray(msg) { |
| 2177 |
var req JSApiLeaderStepdownRequest |
| 2178 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 2179 |
resp.Error = NewJSInvalidJSONError(err) |
| 2180 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2181 |
return |
| 2182 |
} |
| 2183 |
if preferredLeader, resp.Error = s.getStepDownPreferredPlacement(node, req.Placement); resp.Error != nil { |
| 2184 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2185 |
return |
| 2186 |
} |
| 2187 |
} |
| 2188 |
|
| 2189 |
// Call actual stepdown. |
| 2190 |
err = node.StepDown(preferredLeader) |
| 2191 |
if err != nil { |
| 2192 |
resp.Error = NewJSRaftGeneralError(err, Unless(err)) |
| 2193 |
} else { |
| 2194 |
resp.Success = true |
| 2195 |
} |
| 2196 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 2197 |
} |
| 2198 |
|
| 2199 |
// Request to have a consumer leader stepdown. |
| 2200 |
func (s *Server) jsConsumerLeaderStepDownRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 2201 |
if c == nil || !s.JetStreamEnabled() { |
| 2202 |
return |
| 2203 |
} |
| 2204 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 2205 |
if err != nil { |
| 2206 |
s.Warnf(badAPIRequestT, msg) |
| 2207 |
return |
| 2208 |
} |
| 2209 |
|
| 2210 |
var resp = JSApiConsumerLeaderStepDownResponse{ApiResponse: ApiResponse{Type: JSApiConsumerLeaderStepDownResponseType}} |
| 2211 |
|
| 2212 |
// If we are not in clustered mode this is a failed request. |
| 2213 |
if !s.JetStreamIsClustered() { |
| 2214 |
resp.Error = NewJSClusterRequiredError() |
| 2215 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2216 |
return |
| 2217 |
} |
| 2218 |
|
| 2219 |
// If we are here we are clustered. See if we are the stream leader in order to proceed. |
| 2220 |
js, cc := s.getJetStreamCluster() |
| 2221 |
if js == nil || cc == nil { |
| 2222 |
return |
| 2223 |
} |
| 2224 |
if js.isLeaderless() { |
| 2225 |
resp.Error = NewJSClusterNotAvailError() |
| 2226 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2227 |
return |
| 2228 |
} |
| 2229 |
|
| 2230 |
// Have extra token for this one. |
| 2231 |
stream := tokenAt(subject, 6) |
| 2232 |
consumer := tokenAt(subject, 7) |
| 2233 |
|
| 2234 |
js.mu.RLock() |
| 2235 |
isLeader, sa := cc.isLeader(), js.streamAssignmentOrInflight(acc.Name, stream) |
| 2236 |
js.mu.RUnlock() |
| 2237 |
|
| 2238 |
if isLeader && sa == nil { |
| 2239 |
resp.Error = NewJSStreamNotFoundError() |
| 2240 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2241 |
return |
| 2242 |
} else if sa == nil { |
| 2243 |
return |
| 2244 |
} |
| 2245 |
|
| 2246 |
if errorOnRequiredApiLevel(hdr) { |
| 2247 |
resp.Error = NewJSRequiredApiLevelError() |
| 2248 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2249 |
return |
| 2250 |
} |
| 2251 |
|
| 2252 |
var ca *consumerAssignment |
| 2253 |
if sa.consumers != nil { |
| 2254 |
ca = sa.consumers[consumer] |
| 2255 |
} |
| 2256 |
if ca == nil { |
| 2257 |
resp.Error = NewJSConsumerNotFoundError() |
| 2258 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2259 |
return |
| 2260 |
} |
| 2261 |
// Check to see if we are a member of the group and if the group has no leader. |
| 2262 |
if js.isGroupLeaderless(ca.Group) { |
| 2263 |
resp.Error = NewJSClusterNotAvailError() |
| 2264 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2265 |
return |
| 2266 |
} |
| 2267 |
|
| 2268 |
if !acc.JetStreamIsConsumerLeader(stream, consumer) { |
| 2269 |
return |
| 2270 |
} |
| 2271 |
|
| 2272 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 2273 |
if doErr { |
| 2274 |
resp.Error = NewJSNotEnabledForAccountError() |
| 2275 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2276 |
} |
| 2277 |
return |
| 2278 |
} |
| 2279 |
|
| 2280 |
mset, err := acc.lookupStream(stream) |
| 2281 |
if err != nil { |
| 2282 |
resp.Error = NewJSStreamNotFoundError() |
| 2283 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2284 |
return |
| 2285 |
} |
| 2286 |
o := mset.lookupConsumer(consumer) |
| 2287 |
if o == nil { |
| 2288 |
resp.Error = NewJSConsumerNotFoundError() |
| 2289 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2290 |
return |
| 2291 |
} |
| 2292 |
|
| 2293 |
n := o.raftNode() |
| 2294 |
if n == nil { |
| 2295 |
resp.Success = true |
| 2296 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 2297 |
return |
| 2298 |
} |
| 2299 |
|
| 2300 |
var preferredLeader string |
| 2301 |
if isJSONObjectOrArray(msg) { |
| 2302 |
var req JSApiLeaderStepdownRequest |
| 2303 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 2304 |
resp.Error = NewJSInvalidJSONError(err) |
| 2305 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2306 |
return |
| 2307 |
} |
| 2308 |
if preferredLeader, resp.Error = s.getStepDownPreferredPlacement(n, req.Placement); resp.Error != nil { |
| 2309 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2310 |
return |
| 2311 |
} |
| 2312 |
} |
| 2313 |
|
| 2314 |
// Call actual stepdown. |
| 2315 |
err = n.StepDown(preferredLeader) |
| 2316 |
if err != nil { |
| 2317 |
resp.Error = NewJSRaftGeneralError(err, Unless(err)) |
| 2318 |
} else { |
| 2319 |
resp.Success = true |
| 2320 |
} |
| 2321 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 2322 |
} |
| 2323 |
|
| 2324 |
// Request to remove a peer from a clustered stream. |
| 2325 |
func (s *Server) jsStreamRemovePeerRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 2326 |
if c == nil || !s.JetStreamEnabled() { |
| 2327 |
return |
| 2328 |
} |
| 2329 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 2330 |
if err != nil { |
| 2331 |
s.Warnf(badAPIRequestT, msg) |
| 2332 |
return |
| 2333 |
} |
| 2334 |
|
| 2335 |
// Have extra token for this one. |
| 2336 |
name := tokenAt(subject, 6) |
| 2337 |
|
| 2338 |
var resp = JSApiStreamRemovePeerResponse{ApiResponse: ApiResponse{Type: JSApiStreamRemovePeerResponseType}} |
| 2339 |
|
| 2340 |
// If we are not in clustered mode this is a failed request. |
| 2341 |
if !s.JetStreamIsClustered() { |
| 2342 |
resp.Error = NewJSClusterRequiredError() |
| 2343 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2344 |
return |
| 2345 |
} |
| 2346 |
|
| 2347 |
// If we are here we are clustered. See if we are the stream leader in order to proceed. |
| 2348 |
js, cc := s.getJetStreamCluster() |
| 2349 |
if js == nil || cc == nil { |
| 2350 |
return |
| 2351 |
} |
| 2352 |
if js.isLeaderless() { |
| 2353 |
resp.Error = NewJSClusterNotAvailError() |
| 2354 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2355 |
return |
| 2356 |
} |
| 2357 |
|
| 2358 |
js.mu.RLock() |
| 2359 |
isLeader, sa := cc.isLeader(), js.streamAssignmentOrInflight(acc.Name, name) |
| 2360 |
js.mu.RUnlock() |
| 2361 |
|
| 2362 |
// Make sure we are meta leader. |
| 2363 |
if !isLeader { |
| 2364 |
return |
| 2365 |
} |
| 2366 |
|
| 2367 |
if errorOnRequiredApiLevel(hdr) { |
| 2368 |
resp.Error = NewJSRequiredApiLevelError() |
| 2369 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2370 |
return |
| 2371 |
} |
| 2372 |
|
| 2373 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 2374 |
if doErr { |
| 2375 |
resp.Error = NewJSNotEnabledForAccountError() |
| 2376 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2377 |
} |
| 2378 |
return |
| 2379 |
} |
| 2380 |
if isEmptyRequest(msg) { |
| 2381 |
resp.Error = NewJSBadRequestError() |
| 2382 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2383 |
return |
| 2384 |
} |
| 2385 |
|
| 2386 |
var req JSApiStreamRemovePeerRequest |
| 2387 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 2388 |
resp.Error = NewJSInvalidJSONError(err) |
| 2389 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2390 |
return |
| 2391 |
} |
| 2392 |
if req.Peer == _EMPTY_ { |
| 2393 |
resp.Error = NewJSBadRequestError() |
| 2394 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2395 |
return |
| 2396 |
} |
| 2397 |
|
| 2398 |
if sa == nil { |
| 2399 |
// No stream present. |
| 2400 |
resp.Error = NewJSStreamNotFoundError() |
| 2401 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2402 |
return |
| 2403 |
} |
| 2404 |
|
| 2405 |
js.mu.RLock() |
| 2406 |
rg := sa.Group |
| 2407 |
|
| 2408 |
// Check to see if we are a member of the group. |
| 2409 |
// Peer here is either a peer ID or a server name, convert to node name. |
| 2410 |
nodeName := getHash(req.Peer) |
| 2411 |
isMember := rg.isMember(nodeName) |
| 2412 |
if !isMember { |
| 2413 |
nodeName = req.Peer |
| 2414 |
isMember = rg.isMember(nodeName) |
| 2415 |
} |
| 2416 |
js.mu.RUnlock() |
| 2417 |
|
| 2418 |
// Make sure we are a member. |
| 2419 |
if !isMember { |
| 2420 |
resp.Error = NewJSClusterPeerNotMemberError() |
| 2421 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2422 |
return |
| 2423 |
} |
| 2424 |
|
| 2425 |
// If we are here we have a valid peer member set for removal. |
| 2426 |
if !js.removePeerFromStream(sa, nodeName) { |
| 2427 |
resp.Error = NewJSPeerRemapError() |
| 2428 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2429 |
return |
| 2430 |
} |
| 2431 |
|
| 2432 |
resp.Success = true |
| 2433 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 2434 |
} |
| 2435 |
|
| 2436 |
// Request to have the metaleader remove a peer from the system. |
| 2437 |
func (s *Server) jsLeaderServerRemoveRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 2438 |
if c == nil || !s.JetStreamEnabled() { |
| 2439 |
return |
| 2440 |
} |
| 2441 |
|
| 2442 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 2443 |
if err != nil { |
| 2444 |
s.Warnf(badAPIRequestT, msg) |
| 2445 |
return |
| 2446 |
} |
| 2447 |
if acc != s.SystemAccount() { |
| 2448 |
return |
| 2449 |
} |
| 2450 |
|
| 2451 |
js, cc := s.getJetStreamCluster() |
| 2452 |
if js == nil || cc == nil { |
| 2453 |
return |
| 2454 |
} |
| 2455 |
|
| 2456 |
js.mu.RLock() |
| 2457 |
isLeader := cc.isLeader() |
| 2458 |
meta := cc.meta |
| 2459 |
js.mu.RUnlock() |
| 2460 |
|
| 2461 |
// Extra checks here but only leader is listening. |
| 2462 |
if !isLeader { |
| 2463 |
return |
| 2464 |
} |
| 2465 |
|
| 2466 |
var resp = JSApiMetaServerRemoveResponse{ApiResponse: ApiResponse{Type: JSApiMetaServerRemoveResponseType}} |
| 2467 |
if errorOnRequiredApiLevel(hdr) { |
| 2468 |
resp.Error = NewJSRequiredApiLevelError() |
| 2469 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2470 |
return |
| 2471 |
} |
| 2472 |
|
| 2473 |
if isEmptyRequest(msg) { |
| 2474 |
resp.Error = NewJSBadRequestError() |
| 2475 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2476 |
return |
| 2477 |
} |
| 2478 |
|
| 2479 |
var req JSApiMetaServerRemoveRequest |
| 2480 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 2481 |
resp.Error = NewJSInvalidJSONError(err) |
| 2482 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2483 |
return |
| 2484 |
} |
| 2485 |
|
| 2486 |
js.mu.Lock() |
| 2487 |
defer js.mu.Unlock() |
| 2488 |
|
| 2489 |
// Another peer-remove is already in progress, don't allow multiple concurrent changes. |
| 2490 |
if cc.peerRemoveReply != nil { |
| 2491 |
resp.Error = NewJSClusterServerMemberChangeInflightError() |
| 2492 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2493 |
return |
| 2494 |
} |
| 2495 |
|
| 2496 |
var found string |
| 2497 |
for _, p := range meta.Peers() { |
| 2498 |
// If Peer is specified, it takes precedence |
| 2499 |
if req.Peer != _EMPTY_ { |
| 2500 |
if p.ID == req.Peer { |
| 2501 |
found = req.Peer |
| 2502 |
break |
| 2503 |
} |
| 2504 |
continue |
| 2505 |
} |
| 2506 |
si, ok := s.nodeToInfo.Load(p.ID) |
| 2507 |
if ok && si.(nodeInfo).name == req.Server { |
| 2508 |
found = p.ID |
| 2509 |
break |
| 2510 |
} |
| 2511 |
} |
| 2512 |
|
| 2513 |
if found == _EMPTY_ { |
| 2514 |
resp.Error = NewJSClusterServerNotMemberError() |
| 2515 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2516 |
return |
| 2517 |
} |
| 2518 |
|
| 2519 |
if err := meta.ProposeRemovePeer(found); err != nil { |
| 2520 |
if err == errMembershipChange { |
| 2521 |
resp.Error = NewJSClusterServerMemberChangeInflightError() |
| 2522 |
} else { |
| 2523 |
resp.Error = NewJSRaftGeneralError(err) |
| 2524 |
} |
| 2525 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2526 |
return |
| 2527 |
} |
| 2528 |
|
| 2529 |
if cc.peerRemoveReply == nil { |
| 2530 |
cc.peerRemoveReply = make(map[string]peerRemoveInfo, 1) |
| 2531 |
} |
| 2532 |
// Only copy the request, the subject and reply are already copied. |
| 2533 |
cc.peerRemoveReply[found] = peerRemoveInfo{ci: ci, subject: subject, reply: reply, request: string(msg)} |
| 2534 |
} |
| 2535 |
|
| 2536 |
func (s *Server) peerSetToNames(ps []string) []string { |
| 2537 |
names := make([]string, len(ps)) |
| 2538 |
for i := 0; i < len(ps); i++ { |
| 2539 |
if si, ok := s.nodeToInfo.Load(ps[i]); !ok { |
| 2540 |
names[i] = ps[i] |
| 2541 |
} else { |
| 2542 |
names[i] = si.(nodeInfo).name |
| 2543 |
} |
| 2544 |
} |
| 2545 |
return names |
| 2546 |
} |
| 2547 |
|
| 2548 |
// looks up the peer id for a given server name. Cluster and domain name are optional filter criteria |
| 2549 |
func (s *Server) nameToPeer(js *jetStream, serverName, clusterName, domainName string) string { |
| 2550 |
js.mu.RLock() |
| 2551 |
defer js.mu.RUnlock() |
| 2552 |
if cc := js.cluster; cc != nil { |
| 2553 |
for _, p := range cc.meta.Peers() { |
| 2554 |
si, ok := s.nodeToInfo.Load(p.ID) |
| 2555 |
if ok && si.(nodeInfo).name == serverName { |
| 2556 |
if clusterName == _EMPTY_ || clusterName == si.(nodeInfo).cluster { |
| 2557 |
if domainName == _EMPTY_ || domainName == si.(nodeInfo).domain { |
| 2558 |
return p.ID |
| 2559 |
} |
| 2560 |
} |
| 2561 |
} |
| 2562 |
} |
| 2563 |
} |
| 2564 |
return _EMPTY_ |
| 2565 |
} |
| 2566 |
|
| 2567 |
// Request to have the metaleader move a stream on a peer to another |
| 2568 |
func (s *Server) jsLeaderServerStreamMoveRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 2569 |
if c == nil || !s.JetStreamEnabled() { |
| 2570 |
return |
| 2571 |
} |
| 2572 |
|
| 2573 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 2574 |
if err != nil { |
| 2575 |
s.Warnf(badAPIRequestT, msg) |
| 2576 |
return |
| 2577 |
} |
| 2578 |
|
| 2579 |
js, cc := s.getJetStreamCluster() |
| 2580 |
if js == nil || cc == nil { |
| 2581 |
return |
| 2582 |
} |
| 2583 |
|
| 2584 |
// Extra checks here but only leader is listening. |
| 2585 |
js.mu.RLock() |
| 2586 |
isLeader := cc.isLeader() |
| 2587 |
js.mu.RUnlock() |
| 2588 |
|
| 2589 |
if !isLeader { |
| 2590 |
return |
| 2591 |
} |
| 2592 |
|
| 2593 |
accName := tokenAt(subject, 6) |
| 2594 |
streamName := tokenAt(subject, 7) |
| 2595 |
|
| 2596 |
if acc.GetName() != accName && acc != s.SystemAccount() { |
| 2597 |
return |
| 2598 |
} |
| 2599 |
|
| 2600 |
var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}} |
| 2601 |
if errorOnRequiredApiLevel(hdr) { |
| 2602 |
resp.Error = NewJSRequiredApiLevelError() |
| 2603 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2604 |
return |
| 2605 |
} |
| 2606 |
|
| 2607 |
var req JSApiMetaServerStreamMoveRequest |
| 2608 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 2609 |
resp.Error = NewJSInvalidJSONError(err) |
| 2610 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2611 |
return |
| 2612 |
} |
| 2613 |
|
| 2614 |
srcPeer := _EMPTY_ |
| 2615 |
if req.Server != _EMPTY_ { |
| 2616 |
srcPeer = s.nameToPeer(js, req.Server, req.Cluster, req.Domain) |
| 2617 |
} |
| 2618 |
|
| 2619 |
targetAcc, ok := s.accounts.Load(accName) |
| 2620 |
if !ok { |
| 2621 |
resp.Error = NewJSNoAccountError() |
| 2622 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2623 |
return |
| 2624 |
} |
| 2625 |
|
| 2626 |
var streamFound bool |
| 2627 |
cfg := StreamConfig{} |
| 2628 |
currPeers := []string{} |
| 2629 |
currCluster := _EMPTY_ |
| 2630 |
js.mu.RLock() |
| 2631 |
sa := js.streamAssignmentOrInflight(accName, streamName) |
| 2632 |
if sa != nil { |
| 2633 |
cfg = *sa.Config.clone() |
| 2634 |
streamFound = true |
| 2635 |
currPeers = copyStrings(sa.Group.Peers) |
| 2636 |
currCluster = sa.Group.Cluster |
| 2637 |
} |
| 2638 |
js.mu.RUnlock() |
| 2639 |
|
| 2640 |
if !streamFound { |
| 2641 |
resp.Error = NewJSStreamNotFoundError() |
| 2642 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2643 |
return |
| 2644 |
} |
| 2645 |
|
| 2646 |
// if server was picked, make sure src peer exists and move it to first position. |
| 2647 |
// removal will drop peers from the left |
| 2648 |
if req.Server != _EMPTY_ { |
| 2649 |
if srcPeer == _EMPTY_ { |
| 2650 |
resp.Error = NewJSClusterServerNotMemberError() |
| 2651 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2652 |
return |
| 2653 |
} |
| 2654 |
var peerFound bool |
| 2655 |
for i := 0; i < len(currPeers); i++ { |
| 2656 |
if currPeers[i] == srcPeer { |
| 2657 |
copy(currPeers[1:], currPeers[:i]) |
| 2658 |
currPeers[0] = srcPeer |
| 2659 |
peerFound = true |
| 2660 |
break |
| 2661 |
} |
| 2662 |
} |
| 2663 |
if !peerFound { |
| 2664 |
resp.Error = NewJSClusterPeerNotMemberError() |
| 2665 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2666 |
return |
| 2667 |
} |
| 2668 |
} |
| 2669 |
|
| 2670 |
// make sure client is scoped to requested account |
| 2671 |
ciNew := *(ci) |
| 2672 |
ciNew.Account = accName |
| 2673 |
|
| 2674 |
// backup placement such that peers can be looked up with modified tag list |
| 2675 |
var origPlacement *Placement |
| 2676 |
if cfg.Placement != nil { |
| 2677 |
tmp := *cfg.Placement |
| 2678 |
origPlacement = &tmp |
| 2679 |
} |
| 2680 |
|
| 2681 |
if len(req.Tags) > 0 { |
| 2682 |
if cfg.Placement == nil { |
| 2683 |
cfg.Placement = &Placement{} |
| 2684 |
} |
| 2685 |
cfg.Placement.Tags = append(cfg.Placement.Tags, req.Tags...) |
| 2686 |
} |
| 2687 |
|
| 2688 |
peers, e := cc.selectPeerGroup(cfg.Replicas+1, currCluster, &cfg, currPeers, 1, nil) |
| 2689 |
if len(peers) <= cfg.Replicas { |
| 2690 |
// since expanding in the same cluster did not yield a result, try in different cluster |
| 2691 |
peers = nil |
| 2692 |
|
| 2693 |
clusters := map[string]struct{}{} |
| 2694 |
s.nodeToInfo.Range(func(_, ni any) bool { |
| 2695 |
if currCluster != ni.(nodeInfo).cluster { |
| 2696 |
clusters[ni.(nodeInfo).cluster] = struct{}{} |
| 2697 |
} |
| 2698 |
return true |
| 2699 |
}) |
| 2700 |
errs := &selectPeerError{} |
| 2701 |
errs.accumulate(e) |
| 2702 |
for cluster := range clusters { |
| 2703 |
newPeers, e := cc.selectPeerGroup(cfg.Replicas, cluster, &cfg, nil, 0, nil) |
| 2704 |
if len(newPeers) >= cfg.Replicas { |
| 2705 |
peers = append([]string{}, currPeers...) |
| 2706 |
peers = append(peers, newPeers[:cfg.Replicas]...) |
| 2707 |
break |
| 2708 |
} |
| 2709 |
errs.accumulate(e) |
| 2710 |
} |
| 2711 |
if peers == nil { |
| 2712 |
resp.Error = NewJSClusterNoPeersError(errs) |
| 2713 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2714 |
return |
| 2715 |
} |
| 2716 |
} |
| 2717 |
|
| 2718 |
cfg.Placement = origPlacement |
| 2719 |
|
| 2720 |
s.Noticef("Requested move for stream '%s > %s' R=%d from %+v to %+v", |
| 2721 |
accName, streamName, cfg.Replicas, s.peerSetToNames(currPeers), s.peerSetToNames(peers)) |
| 2722 |
|
| 2723 |
// We will always have peers and therefore never do a callout, therefore it is safe to call inline |
| 2724 |
// We should be fine ignoring pedantic mode here. as we do not touch configuration. |
| 2725 |
s.jsClusteredStreamUpdateRequest(&ciNew, targetAcc.(*Account), subject, reply, rmsg, &cfg, peers, false) |
| 2726 |
} |
| 2727 |
|
| 2728 |
// Request to have the metaleader move a stream on a peer to another |
| 2729 |
func (s *Server) jsLeaderServerStreamCancelMoveRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 2730 |
if c == nil || !s.JetStreamEnabled() { |
| 2731 |
return |
| 2732 |
} |
| 2733 |
|
| 2734 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 2735 |
if err != nil { |
| 2736 |
s.Warnf(badAPIRequestT, msg) |
| 2737 |
return |
| 2738 |
} |
| 2739 |
|
| 2740 |
js, cc := s.getJetStreamCluster() |
| 2741 |
if js == nil || cc == nil { |
| 2742 |
return |
| 2743 |
} |
| 2744 |
|
| 2745 |
// Extra checks here but only leader is listening. |
| 2746 |
js.mu.RLock() |
| 2747 |
isLeader := cc.isLeader() |
| 2748 |
js.mu.RUnlock() |
| 2749 |
|
| 2750 |
if !isLeader { |
| 2751 |
return |
| 2752 |
} |
| 2753 |
|
| 2754 |
var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}} |
| 2755 |
if errorOnRequiredApiLevel(hdr) { |
| 2756 |
resp.Error = NewJSRequiredApiLevelError() |
| 2757 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2758 |
return |
| 2759 |
} |
| 2760 |
|
| 2761 |
accName := tokenAt(subject, 6) |
| 2762 |
streamName := tokenAt(subject, 7) |
| 2763 |
|
| 2764 |
if acc.GetName() != accName && acc != s.SystemAccount() { |
| 2765 |
return |
| 2766 |
} |
| 2767 |
|
| 2768 |
targetAcc, ok := s.accounts.Load(accName) |
| 2769 |
if !ok { |
| 2770 |
resp.Error = NewJSNoAccountError() |
| 2771 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2772 |
return |
| 2773 |
} |
| 2774 |
|
| 2775 |
streamFound := false |
| 2776 |
cfg := StreamConfig{} |
| 2777 |
currPeers := []string{} |
| 2778 |
js.mu.RLock() |
| 2779 |
sa := js.streamAssignmentOrInflight(accName, streamName) |
| 2780 |
if sa != nil { |
| 2781 |
cfg = *sa.Config.clone() |
| 2782 |
streamFound = true |
| 2783 |
currPeers = copyStrings(sa.Group.Peers) |
| 2784 |
} |
| 2785 |
js.mu.RUnlock() |
| 2786 |
|
| 2787 |
if !streamFound { |
| 2788 |
resp.Error = NewJSStreamNotFoundError() |
| 2789 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2790 |
return |
| 2791 |
} |
| 2792 |
|
| 2793 |
if len(currPeers) <= cfg.Replicas { |
| 2794 |
resp.Error = NewJSStreamMoveNotInProgressError() |
| 2795 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2796 |
return |
| 2797 |
} |
| 2798 |
|
| 2799 |
// make sure client is scoped to requested account |
| 2800 |
ciNew := *(ci) |
| 2801 |
ciNew.Account = accName |
| 2802 |
|
| 2803 |
peers := currPeers[:cfg.Replicas] |
| 2804 |
|
| 2805 |
// Remove placement in case tags don't match |
| 2806 |
// This can happen if the move was initiated by modifying the tags. |
| 2807 |
// This is an account operation. |
| 2808 |
// This can NOT happen when the move was initiated by the system account. |
| 2809 |
// There move honors the original tag list. |
| 2810 |
if cfg.Placement != nil && len(cfg.Placement.Tags) != 0 { |
| 2811 |
FOR_TAGCHECK: |
| 2812 |
for _, peer := range peers { |
| 2813 |
si, ok := s.nodeToInfo.Load(peer) |
| 2814 |
if !ok { |
| 2815 |
// can't verify tags, do the safe thing and error |
| 2816 |
resp.Error = NewJSStreamGeneralError( |
| 2817 |
fmt.Errorf("peer %s not present for tag validation", peer)) |
| 2818 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2819 |
return |
| 2820 |
} |
| 2821 |
nodeTags := si.(nodeInfo).tags |
| 2822 |
for _, tag := range cfg.Placement.Tags { |
| 2823 |
if !nodeTags.Contains(tag) { |
| 2824 |
// clear placement as tags don't match |
| 2825 |
cfg.Placement = nil |
| 2826 |
break FOR_TAGCHECK |
| 2827 |
} |
| 2828 |
} |
| 2829 |
|
| 2830 |
} |
| 2831 |
} |
| 2832 |
|
| 2833 |
s.Noticef("Requested cancel of move: R=%d '%s > %s' to peer set %+v and restore previous peer set %+v", |
| 2834 |
cfg.Replicas, accName, streamName, s.peerSetToNames(currPeers), s.peerSetToNames(peers)) |
| 2835 |
|
| 2836 |
// We will always have peers and therefore never do a callout, therefore it is safe to call inline |
| 2837 |
s.jsClusteredStreamUpdateRequest(&ciNew, targetAcc.(*Account), subject, reply, rmsg, &cfg, peers, false) |
| 2838 |
} |
| 2839 |
|
| 2840 |
// Request to have an account purged |
| 2841 |
func (s *Server) jsLeaderAccountPurgeRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 2842 |
if c == nil || !s.JetStreamEnabled() { |
| 2843 |
return |
| 2844 |
} |
| 2845 |
|
| 2846 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 2847 |
if err != nil { |
| 2848 |
s.Warnf(badAPIRequestT, msg) |
| 2849 |
return |
| 2850 |
} |
| 2851 |
if acc != s.SystemAccount() { |
| 2852 |
return |
| 2853 |
} |
| 2854 |
|
| 2855 |
js := s.getJetStream() |
| 2856 |
if js == nil { |
| 2857 |
return |
| 2858 |
} |
| 2859 |
|
| 2860 |
accName := tokenAt(subject, 5) |
| 2861 |
|
| 2862 |
var resp = JSApiAccountPurgeResponse{ApiResponse: ApiResponse{Type: JSApiAccountPurgeResponseType}} |
| 2863 |
|
| 2864 |
// Check for path like separators in the name. |
| 2865 |
if strings.ContainsAny(accName, `\/`) { |
| 2866 |
resp.Error = NewJSStreamGeneralError(errors.New("account name can not contain path separators")) |
| 2867 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2868 |
return |
| 2869 |
} |
| 2870 |
|
| 2871 |
if !s.JetStreamIsClustered() { |
| 2872 |
var streams []*stream |
| 2873 |
var ac *Account |
| 2874 |
if ac, err = s.lookupAccount(accName); err == nil && ac != nil { |
| 2875 |
streams = ac.streams() |
| 2876 |
} |
| 2877 |
|
| 2878 |
s.Noticef("Purge request for account %s (streams: %d, hasAccount: %t)", |
| 2879 |
accName, len(streams), ac != nil) |
| 2880 |
|
| 2881 |
for _, mset := range streams { |
| 2882 |
err := mset.delete() |
| 2883 |
if err != nil { |
| 2884 |
resp.Error = NewJSStreamDeleteError(err) |
| 2885 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2886 |
return |
| 2887 |
} |
| 2888 |
} |
| 2889 |
if err := os.RemoveAll(filepath.Join(js.config.StoreDir, accName)); err != nil { |
| 2890 |
resp.Error = NewJSStreamGeneralError(err) |
| 2891 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2892 |
return |
| 2893 |
} |
| 2894 |
resp.Initiated = true |
| 2895 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2896 |
return |
| 2897 |
} |
| 2898 |
|
| 2899 |
_, cc := s.getJetStreamCluster() |
| 2900 |
|
| 2901 |
js.mu.RLock() |
| 2902 |
isLeader := cc.isLeader() |
| 2903 |
meta := cc.meta |
| 2904 |
js.mu.RUnlock() |
| 2905 |
|
| 2906 |
if !isLeader { |
| 2907 |
return |
| 2908 |
} |
| 2909 |
|
| 2910 |
if errorOnRequiredApiLevel(hdr) { |
| 2911 |
resp.Error = NewJSRequiredApiLevelError() |
| 2912 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2913 |
return |
| 2914 |
} |
| 2915 |
|
| 2916 |
if js.isMetaRecovering() { |
| 2917 |
// While in recovery mode, the data structures are not fully initialized |
| 2918 |
resp.Error = NewJSClusterNotAvailError() |
| 2919 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2920 |
return |
| 2921 |
} |
| 2922 |
|
| 2923 |
js.mu.Lock() |
| 2924 |
ns, nc := 0, 0 |
| 2925 |
for osa := range js.streamAssignmentsOrInflightSeq(accName) { |
| 2926 |
for oca := range js.consumerAssignmentsOrInflightSeq(accName, osa.Config.Name) { |
| 2927 |
ca := &consumerAssignment{Group: oca.Group, Stream: oca.Stream, Name: oca.Name, Config: oca.Config, Subject: subject, Client: oca.Client, Created: oca.Created} |
| 2928 |
if err = meta.Propose(cc.term, encodeDeleteConsumerAssignment(ca)); err != nil { |
| 2929 |
js.mu.Unlock() |
| 2930 |
resp.Error = NewJSStreamGeneralError(err) |
| 2931 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2932 |
return |
| 2933 |
} |
| 2934 |
cc.trackInflightConsumerProposal(accName, osa.Config.Name, ca, true) |
| 2935 |
nc++ |
| 2936 |
} |
| 2937 |
sa := &streamAssignment{Group: osa.Group, Config: osa.Config, Subject: subject, Client: osa.Client, Created: osa.Created} |
| 2938 |
if err = meta.Propose(cc.term, encodeDeleteStreamAssignment(sa)); err != nil { |
| 2939 |
js.mu.Unlock() |
| 2940 |
resp.Error = NewJSStreamGeneralError(err) |
| 2941 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2942 |
return |
| 2943 |
} |
| 2944 |
cc.trackInflightStreamProposal(accName, sa, true) |
| 2945 |
ns++ |
| 2946 |
} |
| 2947 |
js.mu.Unlock() |
| 2948 |
|
| 2949 |
hasAccount := ns > 0 |
| 2950 |
s.Noticef("Purge request for account %s (streams: %d, consumer: %d, hasAccount: %t)", accName, ns, nc, hasAccount) |
| 2951 |
|
| 2952 |
resp.Initiated = true |
| 2953 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2954 |
} |
| 2955 |
|
| 2956 |
// Request to have the meta leader stepdown. |
| 2957 |
// These will only be received by the meta leader, so less checking needed. |
| 2958 |
func (s *Server) jsLeaderStepDownRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 2959 |
if c == nil || !s.JetStreamEnabled() { |
| 2960 |
return |
| 2961 |
} |
| 2962 |
|
| 2963 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 2964 |
if err != nil { |
| 2965 |
s.Warnf(badAPIRequestT, msg) |
| 2966 |
return |
| 2967 |
} |
| 2968 |
|
| 2969 |
// This should only be coming from the System Account. |
| 2970 |
if acc != s.SystemAccount() { |
| 2971 |
s.RateLimitWarnf("JetStream API stepdown request from non-system account: %q user: %q", ci.serviceAccount(), ci.User) |
| 2972 |
return |
| 2973 |
} |
| 2974 |
|
| 2975 |
js, cc := s.getJetStreamCluster() |
| 2976 |
if js == nil || cc == nil { |
| 2977 |
return |
| 2978 |
} |
| 2979 |
|
| 2980 |
// Extra checks here but only leader is listening. |
| 2981 |
js.mu.RLock() |
| 2982 |
isLeader := cc.isLeader() |
| 2983 |
meta := cc.meta |
| 2984 |
js.mu.RUnlock() |
| 2985 |
|
| 2986 |
if !isLeader { |
| 2987 |
return |
| 2988 |
} |
| 2989 |
|
| 2990 |
var preferredLeader string |
| 2991 |
var resp = JSApiLeaderStepDownResponse{ApiResponse: ApiResponse{Type: JSApiLeaderStepDownResponseType}} |
| 2992 |
if errorOnRequiredApiLevel(hdr) { |
| 2993 |
resp.Error = NewJSRequiredApiLevelError() |
| 2994 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 2995 |
return |
| 2996 |
} |
| 2997 |
|
| 2998 |
if isJSONObjectOrArray(msg) { |
| 2999 |
var req JSApiLeaderStepdownRequest |
| 3000 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 3001 |
resp.Error = NewJSInvalidJSONError(err) |
| 3002 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3003 |
return |
| 3004 |
} |
| 3005 |
if preferredLeader, resp.Error = s.getStepDownPreferredPlacement(meta, req.Placement); resp.Error != nil { |
| 3006 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3007 |
return |
| 3008 |
} |
| 3009 |
} |
| 3010 |
|
| 3011 |
// Call actual stepdown. |
| 3012 |
err = meta.StepDown(preferredLeader) |
| 3013 |
if err != nil { |
| 3014 |
resp.Error = NewJSRaftGeneralError(err, Unless(err)) |
| 3015 |
} else { |
| 3016 |
resp.Success = true |
| 3017 |
} |
| 3018 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 3019 |
} |
| 3020 |
|
| 3021 |
// Check if given []bytes is a JSON Object or Array. |
| 3022 |
// Technically, valid JSON can also be a plain string or number, but for our use case, |
| 3023 |
// we care only for JSON objects or arrays which starts with `[` or `{`. |
| 3024 |
// This function does not have to ensure valid JSON in its entirety. It is used merely |
| 3025 |
// to hint the codepath if it should attempt to parse the request as JSON or not. |
| 3026 |
func isJSONObjectOrArray(req []byte) bool { |
| 3027 |
// Skip leading JSON whitespace (space, tab, newline, carriage return) |
| 3028 |
i := 0 |
| 3029 |
for i < len(req) && (req[i] == ' ' || req[i] == '\t' || req[i] == '\n' || req[i] == '\r') { |
| 3030 |
i++ |
| 3031 |
} |
| 3032 |
// Check for empty input after trimming |
| 3033 |
if i >= len(req) { |
| 3034 |
return false |
| 3035 |
} |
| 3036 |
// Check if the first non-whitespace character is '{' or '[' |
| 3037 |
return req[i] == '{' || req[i] == '[' |
| 3038 |
} |
| 3039 |
|
| 3040 |
func isEmptyRequest(req []byte) bool { |
| 3041 |
if len(req) == 0 { |
| 3042 |
return true |
| 3043 |
} |
| 3044 |
if bytes.Equal(req, []byte("{}")) { |
| 3045 |
return true |
| 3046 |
} |
| 3047 |
// If we are here we didn't get our simple match, but still could be valid. |
| 3048 |
var v any |
| 3049 |
if err := json.Unmarshal(req, &v); err != nil { |
| 3050 |
return false |
| 3051 |
} |
| 3052 |
vm, ok := v.(map[string]any) |
| 3053 |
if !ok { |
| 3054 |
return false |
| 3055 |
} |
| 3056 |
return len(vm) == 0 |
| 3057 |
} |
| 3058 |
|
| 3059 |
// getStepDownPreferredPlacement attempts to work out what the best placement is |
| 3060 |
// for a stepdown request. The preferred server name always takes precedence, but |
| 3061 |
// if not specified, the placement will be used to filter by cluster. The caller |
| 3062 |
// should check for return API errors and return those to the requestor if needed. |
| 3063 |
func (s *Server) getStepDownPreferredPlacement(group RaftNode, placement *Placement) (string, *ApiError) { |
| 3064 |
if placement == nil { |
| 3065 |
return _EMPTY_, nil |
| 3066 |
} |
| 3067 |
var preferredLeader string |
| 3068 |
if placement.Preferred != _EMPTY_ { |
| 3069 |
for _, p := range group.Peers() { |
| 3070 |
si, ok := s.nodeToInfo.Load(p.ID) |
| 3071 |
if !ok || si == nil { |
| 3072 |
continue |
| 3073 |
} |
| 3074 |
if si.(nodeInfo).name == placement.Preferred { |
| 3075 |
preferredLeader = p.ID |
| 3076 |
break |
| 3077 |
} |
| 3078 |
} |
| 3079 |
if preferredLeader == group.ID() { |
| 3080 |
return _EMPTY_, NewJSClusterNoPeersError(fmt.Errorf("preferred server %q is already leader", placement.Preferred)) |
| 3081 |
} |
| 3082 |
if preferredLeader == _EMPTY_ { |
| 3083 |
return _EMPTY_, NewJSClusterNoPeersError(fmt.Errorf("preferred server %q not known", placement.Preferred)) |
| 3084 |
} |
| 3085 |
} else { |
| 3086 |
possiblePeers := make(map[*Peer]nodeInfo, len(group.Peers())) |
| 3087 |
ourID := group.ID() |
| 3088 |
for _, p := range group.Peers() { |
| 3089 |
if p == nil { |
| 3090 |
continue // ... shouldn't happen. |
| 3091 |
} |
| 3092 |
si, ok := s.nodeToInfo.Load(p.ID) |
| 3093 |
if !ok || si == nil { |
| 3094 |
continue |
| 3095 |
} |
| 3096 |
ni := si.(nodeInfo) |
| 3097 |
if ni.offline || p.ID == ourID { |
| 3098 |
continue |
| 3099 |
} |
| 3100 |
possiblePeers[p] = ni |
| 3101 |
} |
| 3102 |
// If cluster is specified, filter out anything not matching the cluster name. |
| 3103 |
if placement.Cluster != _EMPTY_ { |
| 3104 |
for p, si := range possiblePeers { |
| 3105 |
if si.cluster != placement.Cluster { |
| 3106 |
delete(possiblePeers, p) |
| 3107 |
} |
| 3108 |
} |
| 3109 |
} |
| 3110 |
// If tags are specified, filter out anything not matching all supplied tags. |
| 3111 |
if len(placement.Tags) > 0 { |
| 3112 |
for p, si := range possiblePeers { |
| 3113 |
matchesAll := true |
| 3114 |
for _, tag := range placement.Tags { |
| 3115 |
if matchesAll = matchesAll && si.tags.Contains(tag); !matchesAll { |
| 3116 |
break |
| 3117 |
} |
| 3118 |
} |
| 3119 |
if !matchesAll { |
| 3120 |
delete(possiblePeers, p) |
| 3121 |
} |
| 3122 |
} |
| 3123 |
} |
| 3124 |
// If there are no possible peers, return an error. |
| 3125 |
if len(possiblePeers) == 0 { |
| 3126 |
return _EMPTY_, NewJSClusterNoPeersError(fmt.Errorf("no replacement peer connected")) |
| 3127 |
} |
| 3128 |
// Take advantage of random map iteration order to select the preferred. |
| 3129 |
for p := range possiblePeers { |
| 3130 |
preferredLeader = p.ID |
| 3131 |
break |
| 3132 |
} |
| 3133 |
} |
| 3134 |
return preferredLeader, nil |
| 3135 |
} |
| 3136 |
|
| 3137 |
// Request to delete a stream. |
| 3138 |
func (s *Server) jsStreamDeleteRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 3139 |
if c == nil || !s.JetStreamEnabled() { |
| 3140 |
return |
| 3141 |
} |
| 3142 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 3143 |
if err != nil { |
| 3144 |
s.Warnf(badAPIRequestT, msg) |
| 3145 |
return |
| 3146 |
} |
| 3147 |
|
| 3148 |
var resp = JSApiStreamDeleteResponse{ApiResponse: ApiResponse{Type: JSApiStreamDeleteResponseType}} |
| 3149 |
|
| 3150 |
// Determine if we should proceed here when we are in clustered mode. |
| 3151 |
if s.JetStreamIsClustered() { |
| 3152 |
js, cc := s.getJetStreamCluster() |
| 3153 |
if js == nil || cc == nil { |
| 3154 |
return |
| 3155 |
} |
| 3156 |
if js.isLeaderless() { |
| 3157 |
resp.Error = NewJSClusterNotAvailError() |
| 3158 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3159 |
return |
| 3160 |
} |
| 3161 |
// Make sure we are meta leader. |
| 3162 |
if !s.JetStreamIsLeader() { |
| 3163 |
return |
| 3164 |
} |
| 3165 |
} |
| 3166 |
|
| 3167 |
if errorOnRequiredApiLevel(hdr) { |
| 3168 |
resp.Error = NewJSRequiredApiLevelError() |
| 3169 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3170 |
return |
| 3171 |
} |
| 3172 |
|
| 3173 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3174 |
if doErr { |
| 3175 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3176 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3177 |
} |
| 3178 |
return |
| 3179 |
} |
| 3180 |
|
| 3181 |
if !isEmptyRequest(msg) { |
| 3182 |
resp.Error = NewJSNotEmptyRequestError() |
| 3183 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3184 |
return |
| 3185 |
} |
| 3186 |
stream := streamNameFromSubject(subject) |
| 3187 |
|
| 3188 |
// Clustered. |
| 3189 |
if s.JetStreamIsClustered() { |
| 3190 |
s.jsClusteredStreamDeleteRequest(ci, acc, stream, subject, reply, msg) |
| 3191 |
return |
| 3192 |
} |
| 3193 |
|
| 3194 |
mset, err := acc.lookupStream(stream) |
| 3195 |
if err != nil { |
| 3196 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 3197 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3198 |
return |
| 3199 |
} |
| 3200 |
|
| 3201 |
if err := mset.delete(); err != nil { |
| 3202 |
resp.Error = NewJSStreamDeleteError(err, Unless(err)) |
| 3203 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3204 |
return |
| 3205 |
} |
| 3206 |
resp.Success = true |
| 3207 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 3208 |
} |
| 3209 |
|
| 3210 |
// Request to delete a message. |
| 3211 |
// This expects a stream sequence number as the msg body. |
| 3212 |
func (s *Server) jsMsgDeleteRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 3213 |
if c == nil || !s.JetStreamEnabled() { |
| 3214 |
return |
| 3215 |
} |
| 3216 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 3217 |
if err != nil { |
| 3218 |
s.Warnf(badAPIRequestT, msg) |
| 3219 |
return |
| 3220 |
} |
| 3221 |
|
| 3222 |
stream := tokenAt(subject, 6) |
| 3223 |
|
| 3224 |
var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}} |
| 3225 |
|
| 3226 |
// If we are in clustered mode we need to be the stream leader to proceed. |
| 3227 |
if s.JetStreamIsClustered() { |
| 3228 |
// Check to make sure the stream is assigned. |
| 3229 |
js, cc := s.getJetStreamCluster() |
| 3230 |
if js == nil || cc == nil { |
| 3231 |
return |
| 3232 |
} |
| 3233 |
if js.isLeaderless() { |
| 3234 |
resp.Error = NewJSClusterNotAvailError() |
| 3235 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3236 |
return |
| 3237 |
} |
| 3238 |
|
| 3239 |
js.mu.RLock() |
| 3240 |
isLeader, sa := cc.isLeader(), js.streamAssignmentOrInflight(acc.Name, stream) |
| 3241 |
js.mu.RUnlock() |
| 3242 |
|
| 3243 |
if isLeader && sa == nil { |
| 3244 |
// We can't find the stream, so mimic what would be the errors below. |
| 3245 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3246 |
if doErr { |
| 3247 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3248 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3249 |
} |
| 3250 |
return |
| 3251 |
} |
| 3252 |
// No stream present. |
| 3253 |
resp.Error = NewJSStreamNotFoundError() |
| 3254 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3255 |
return |
| 3256 |
} else if sa == nil { |
| 3257 |
return |
| 3258 |
} |
| 3259 |
|
| 3260 |
// Check to see if we are a member of the group and if the group has no leader. |
| 3261 |
if js.isGroupLeaderless(sa.Group) { |
| 3262 |
resp.Error = NewJSClusterNotAvailError() |
| 3263 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3264 |
return |
| 3265 |
} |
| 3266 |
|
| 3267 |
// We have the stream assigned and a leader, so only the stream leader should answer. |
| 3268 |
if !acc.JetStreamIsStreamLeader(stream) { |
| 3269 |
return |
| 3270 |
} |
| 3271 |
} |
| 3272 |
|
| 3273 |
if errorOnRequiredApiLevel(hdr) { |
| 3274 |
resp.Error = NewJSRequiredApiLevelError() |
| 3275 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3276 |
return |
| 3277 |
} |
| 3278 |
|
| 3279 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3280 |
if doErr { |
| 3281 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3282 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3283 |
} |
| 3284 |
return |
| 3285 |
} |
| 3286 |
if isEmptyRequest(msg) { |
| 3287 |
resp.Error = NewJSBadRequestError() |
| 3288 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3289 |
return |
| 3290 |
} |
| 3291 |
var req JSApiMsgDeleteRequest |
| 3292 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 3293 |
resp.Error = NewJSInvalidJSONError(err) |
| 3294 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3295 |
return |
| 3296 |
} |
| 3297 |
|
| 3298 |
mset, err := acc.lookupStream(stream) |
| 3299 |
if err != nil { |
| 3300 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 3301 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3302 |
return |
| 3303 |
} |
| 3304 |
mset.cfgMu.RLock() |
| 3305 |
sealed, denyDelete := mset.cfg.Sealed, mset.cfg.DenyDelete |
| 3306 |
mset.cfgMu.RUnlock() |
| 3307 |
if sealed { |
| 3308 |
resp.Error = NewJSStreamSealedError() |
| 3309 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3310 |
return |
| 3311 |
} |
| 3312 |
if denyDelete { |
| 3313 |
resp.Error = NewJSStreamMsgDeleteFailedError(errors.New("message delete not permitted")) |
| 3314 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3315 |
return |
| 3316 |
} |
| 3317 |
|
| 3318 |
if s.JetStreamIsClustered() { |
| 3319 |
s.jsClusteredMsgDeleteRequest(ci, acc, mset, stream, subject, reply, &req, rmsg) |
| 3320 |
return |
| 3321 |
} |
| 3322 |
|
| 3323 |
var removed bool |
| 3324 |
if req.NoErase { |
| 3325 |
removed, err = mset.removeMsg(req.Seq) |
| 3326 |
} else { |
| 3327 |
removed, err = mset.eraseMsg(req.Seq) |
| 3328 |
} |
| 3329 |
if err != nil { |
| 3330 |
resp.Error = NewJSStreamMsgDeleteFailedError(err, Unless(err)) |
| 3331 |
} else if !removed { |
| 3332 |
resp.Error = NewJSSequenceNotFoundError(req.Seq) |
| 3333 |
} else { |
| 3334 |
resp.Success = true |
| 3335 |
} |
| 3336 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 3337 |
} |
| 3338 |
|
| 3339 |
// Request to get a raw stream message. |
| 3340 |
func (s *Server) jsMsgGetRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 3341 |
if c == nil || !s.JetStreamEnabled() { |
| 3342 |
return |
| 3343 |
} |
| 3344 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 3345 |
if err != nil { |
| 3346 |
s.Warnf(badAPIRequestT, msg) |
| 3347 |
return |
| 3348 |
} |
| 3349 |
|
| 3350 |
stream := tokenAt(subject, 6) |
| 3351 |
|
| 3352 |
var resp = JSApiMsgGetResponse{ApiResponse: ApiResponse{Type: JSApiMsgGetResponseType}} |
| 3353 |
|
| 3354 |
// If we are in clustered mode we need to be the stream leader to proceed. |
| 3355 |
if s.JetStreamIsClustered() { |
| 3356 |
// Check to make sure the stream is assigned. |
| 3357 |
js, cc := s.getJetStreamCluster() |
| 3358 |
if js == nil || cc == nil { |
| 3359 |
return |
| 3360 |
} |
| 3361 |
if js.isLeaderless() { |
| 3362 |
resp.Error = NewJSClusterNotAvailError() |
| 3363 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3364 |
return |
| 3365 |
} |
| 3366 |
|
| 3367 |
js.mu.RLock() |
| 3368 |
isLeader, sa := cc.isLeader(), js.streamAssignmentOrInflight(acc.Name, stream) |
| 3369 |
js.mu.RUnlock() |
| 3370 |
|
| 3371 |
if isLeader && sa == nil { |
| 3372 |
// We can't find the stream, so mimic what would be the errors below. |
| 3373 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3374 |
if doErr { |
| 3375 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3376 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3377 |
} |
| 3378 |
return |
| 3379 |
} |
| 3380 |
// No stream present. |
| 3381 |
resp.Error = NewJSStreamNotFoundError() |
| 3382 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3383 |
return |
| 3384 |
} else if sa == nil { |
| 3385 |
return |
| 3386 |
} |
| 3387 |
|
| 3388 |
// Check to see if we are a member of the group and if the group has no leader. |
| 3389 |
if js.isGroupLeaderless(sa.Group) { |
| 3390 |
resp.Error = NewJSClusterNotAvailError() |
| 3391 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3392 |
return |
| 3393 |
} |
| 3394 |
|
| 3395 |
// We have the stream assigned and a leader, so only the stream leader should answer. |
| 3396 |
if !acc.JetStreamIsStreamLeader(stream) { |
| 3397 |
return |
| 3398 |
} |
| 3399 |
} |
| 3400 |
|
| 3401 |
if errorOnRequiredApiLevel(hdr) { |
| 3402 |
resp.Error = NewJSRequiredApiLevelError() |
| 3403 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3404 |
return |
| 3405 |
} |
| 3406 |
|
| 3407 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3408 |
if doErr { |
| 3409 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3410 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3411 |
} |
| 3412 |
return |
| 3413 |
} |
| 3414 |
if isEmptyRequest(msg) { |
| 3415 |
resp.Error = NewJSBadRequestError() |
| 3416 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3417 |
return |
| 3418 |
} |
| 3419 |
var req JSApiMsgGetRequest |
| 3420 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 3421 |
resp.Error = NewJSInvalidJSONError(err) |
| 3422 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3423 |
return |
| 3424 |
} |
| 3425 |
|
| 3426 |
// This version does not support batch. |
| 3427 |
if req.Batch > 0 || req.MaxBytes > 0 { |
| 3428 |
resp.Error = NewJSBadRequestError() |
| 3429 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3430 |
return |
| 3431 |
} |
| 3432 |
|
| 3433 |
// Validate non-conflicting options. Seq, LastFor, and AsOfTime are mutually exclusive. |
| 3434 |
// NextFor can be paired with Seq or AsOfTime indicating a filter subject. |
| 3435 |
if (req.Seq > 0 && req.LastFor != _EMPTY_) || |
| 3436 |
(req.Seq == 0 && req.LastFor == _EMPTY_ && req.NextFor == _EMPTY_ && req.StartTime == nil) || |
| 3437 |
(req.Seq > 0 && req.StartTime != nil) || |
| 3438 |
(req.StartTime != nil && req.LastFor != _EMPTY_) || |
| 3439 |
(req.LastFor != _EMPTY_ && req.NextFor != _EMPTY_) { |
| 3440 |
resp.Error = NewJSBadRequestError() |
| 3441 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3442 |
return |
| 3443 |
} |
| 3444 |
|
| 3445 |
mset, err := acc.lookupStream(stream) |
| 3446 |
if err != nil { |
| 3447 |
resp.Error = NewJSStreamNotFoundError() |
| 3448 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3449 |
return |
| 3450 |
} |
| 3451 |
if mset.offlineReason != _EMPTY_ { |
| 3452 |
// Just let the request time out. |
| 3453 |
return |
| 3454 |
} |
| 3455 |
|
| 3456 |
var svp StoreMsg |
| 3457 |
var sm *StoreMsg |
| 3458 |
|
| 3459 |
// Ensure this read request is isolated and doesn't interleave with writes. |
| 3460 |
mset.isolateMu.RLock() |
| 3461 |
defer mset.isolateMu.RUnlock() |
| 3462 |
|
| 3463 |
// If AsOfTime is set, perform this first to get the sequence. |
| 3464 |
var seq uint64 |
| 3465 |
if req.StartTime != nil { |
| 3466 |
seq = mset.store.GetSeqFromTime(*req.StartTime) |
| 3467 |
} else { |
| 3468 |
seq = req.Seq |
| 3469 |
} |
| 3470 |
|
| 3471 |
if seq > 0 && req.NextFor == _EMPTY_ { |
| 3472 |
sm, err = mset.store.LoadMsg(seq, &svp) |
| 3473 |
} else if req.NextFor != _EMPTY_ { |
| 3474 |
sm, _, err = mset.store.LoadNextMsg(req.NextFor, subjectHasWildcard(req.NextFor), seq, &svp) |
| 3475 |
} else { |
| 3476 |
sm, err = mset.store.LoadLastMsg(req.LastFor, &svp) |
| 3477 |
} |
| 3478 |
if err != nil { |
| 3479 |
resp.Error = NewJSNoMessageFoundError() |
| 3480 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3481 |
return |
| 3482 |
} |
| 3483 |
resp.Message = &StoredMsg{ |
| 3484 |
Subject: sm.subj, |
| 3485 |
Sequence: sm.seq, |
| 3486 |
Data: sm.msg, |
| 3487 |
Time: time.Unix(0, sm.ts).UTC(), |
| 3488 |
} |
| 3489 |
if !req.NoHeaders { |
| 3490 |
resp.Message.Header = sm.hdr |
| 3491 |
} |
| 3492 |
|
| 3493 |
// Don't send response through API layer for this call. |
| 3494 |
s.sendInternalAccountMsg(nil, reply, s.jsonResponse(resp)) |
| 3495 |
} |
| 3496 |
|
| 3497 |
func (s *Server) jsConsumerUnpinRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 3498 |
if c == nil || !s.JetStreamEnabled() { |
| 3499 |
return |
| 3500 |
} |
| 3501 |
|
| 3502 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 3503 |
if err != nil { |
| 3504 |
s.Warnf(badAPIRequestT, msg) |
| 3505 |
return |
| 3506 |
} |
| 3507 |
|
| 3508 |
stream := streamNameFromSubject(subject) |
| 3509 |
consumer := consumerNameFromSubject(subject) |
| 3510 |
|
| 3511 |
var resp = JSApiConsumerUnpinResponse{ApiResponse: ApiResponse{Type: JSApiConsumerUnpinResponseType}} |
| 3512 |
|
| 3513 |
if s.JetStreamIsClustered() { |
| 3514 |
// Check to make sure the stream is assigned. |
| 3515 |
js, cc := s.getJetStreamCluster() |
| 3516 |
if js == nil || cc == nil { |
| 3517 |
return |
| 3518 |
} |
| 3519 |
|
| 3520 |
// First check if the stream and consumer is there. |
| 3521 |
js.mu.RLock() |
| 3522 |
sa := js.streamAssignment(acc.Name, stream) |
| 3523 |
if sa == nil { |
| 3524 |
js.mu.RUnlock() |
| 3525 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 3526 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3527 |
return |
| 3528 |
} |
| 3529 |
if sa.unsupported != nil { |
| 3530 |
js.mu.RUnlock() |
| 3531 |
// Just let the request time out. |
| 3532 |
return |
| 3533 |
} |
| 3534 |
|
| 3535 |
ca, ok := sa.consumers[consumer] |
| 3536 |
if !ok || ca == nil { |
| 3537 |
js.mu.RUnlock() |
| 3538 |
resp.Error = NewJSConsumerNotFoundError() |
| 3539 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3540 |
return |
| 3541 |
} |
| 3542 |
if ca.unsupported != nil { |
| 3543 |
js.mu.RUnlock() |
| 3544 |
// Just let the request time out. |
| 3545 |
return |
| 3546 |
} |
| 3547 |
js.mu.RUnlock() |
| 3548 |
|
| 3549 |
// Then check if we are the leader. |
| 3550 |
mset, err := acc.lookupStream(stream) |
| 3551 |
if err != nil { |
| 3552 |
return |
| 3553 |
} |
| 3554 |
|
| 3555 |
o := mset.lookupConsumer(consumer) |
| 3556 |
if o == nil { |
| 3557 |
return |
| 3558 |
} |
| 3559 |
if !o.isLeader() { |
| 3560 |
return |
| 3561 |
} |
| 3562 |
} |
| 3563 |
|
| 3564 |
if errorOnRequiredApiLevel(hdr) { |
| 3565 |
resp.Error = NewJSRequiredApiLevelError() |
| 3566 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3567 |
return |
| 3568 |
} |
| 3569 |
|
| 3570 |
var req JSApiConsumerUnpinRequest |
| 3571 |
if err := json.Unmarshal(msg, &req); err != nil { |
| 3572 |
resp.Error = NewJSInvalidJSONError(err) |
| 3573 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3574 |
return |
| 3575 |
} |
| 3576 |
|
| 3577 |
if req.Group == _EMPTY_ { |
| 3578 |
resp.Error = NewJSInvalidJSONError(errors.New("consumer group not specified")) |
| 3579 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3580 |
return |
| 3581 |
} |
| 3582 |
|
| 3583 |
if !validGroupName.MatchString(req.Group) { |
| 3584 |
resp.Error = NewJSConsumerInvalidGroupNameError() |
| 3585 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3586 |
return |
| 3587 |
} |
| 3588 |
|
| 3589 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3590 |
if doErr { |
| 3591 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3592 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3593 |
} |
| 3594 |
return |
| 3595 |
} |
| 3596 |
|
| 3597 |
mset, err := acc.lookupStream(stream) |
| 3598 |
if err != nil { |
| 3599 |
resp.Error = NewJSStreamNotFoundError() |
| 3600 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3601 |
return |
| 3602 |
} |
| 3603 |
if mset.offlineReason != _EMPTY_ { |
| 3604 |
// Just let the request time out. |
| 3605 |
return |
| 3606 |
} |
| 3607 |
o := mset.lookupConsumer(consumer) |
| 3608 |
if o == nil { |
| 3609 |
resp.Error = NewJSConsumerNotFoundError() |
| 3610 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3611 |
return |
| 3612 |
} |
| 3613 |
if o.offlineReason != _EMPTY_ { |
| 3614 |
// Just let the request time out. |
| 3615 |
return |
| 3616 |
} |
| 3617 |
|
| 3618 |
var foundPriority bool |
| 3619 |
for _, group := range o.config().PriorityGroups { |
| 3620 |
if group == req.Group { |
| 3621 |
foundPriority = true |
| 3622 |
break |
| 3623 |
} |
| 3624 |
} |
| 3625 |
if !foundPriority { |
| 3626 |
resp.Error = NewJSConsumerInvalidPriorityGroupError() |
| 3627 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3628 |
return |
| 3629 |
} |
| 3630 |
|
| 3631 |
o.mu.Lock() |
| 3632 |
o.unassignPinId() |
| 3633 |
o.sendUnpinnedAdvisoryLocked(req.Group, "admin") |
| 3634 |
o.mu.Unlock() |
| 3635 |
o.signalNewMessages() |
| 3636 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 3637 |
} |
| 3638 |
|
| 3639 |
// Request to purge a stream. |
| 3640 |
func (s *Server) jsStreamPurgeRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 3641 |
if c == nil || !s.JetStreamEnabled() { |
| 3642 |
return |
| 3643 |
} |
| 3644 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 3645 |
if err != nil { |
| 3646 |
s.Warnf(badAPIRequestT, msg) |
| 3647 |
return |
| 3648 |
} |
| 3649 |
|
| 3650 |
stream := streamNameFromSubject(subject) |
| 3651 |
|
| 3652 |
var resp = JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}} |
| 3653 |
|
| 3654 |
// If we are in clustered mode we need to be the stream leader to proceed. |
| 3655 |
if s.JetStreamIsClustered() { |
| 3656 |
// Check to make sure the stream is assigned. |
| 3657 |
js, cc := s.getJetStreamCluster() |
| 3658 |
if js == nil || cc == nil { |
| 3659 |
return |
| 3660 |
} |
| 3661 |
|
| 3662 |
js.mu.RLock() |
| 3663 |
isLeader, sa := cc.isLeader(), js.streamAssignmentOrInflight(acc.Name, stream) |
| 3664 |
js.mu.RUnlock() |
| 3665 |
|
| 3666 |
if isLeader && sa == nil { |
| 3667 |
// We can't find the stream, so mimic what would be the errors below. |
| 3668 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3669 |
if doErr { |
| 3670 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3671 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3672 |
} |
| 3673 |
return |
| 3674 |
} |
| 3675 |
// No stream present. |
| 3676 |
resp.Error = NewJSStreamNotFoundError() |
| 3677 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3678 |
return |
| 3679 |
} else if sa == nil { |
| 3680 |
if js.isLeaderless() { |
| 3681 |
resp.Error = NewJSClusterNotAvailError() |
| 3682 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3683 |
} |
| 3684 |
return |
| 3685 |
} |
| 3686 |
|
| 3687 |
// Check to see if we are a member of the group and if the group has no leader. |
| 3688 |
if js.isGroupLeaderless(sa.Group) { |
| 3689 |
resp.Error = NewJSClusterNotAvailError() |
| 3690 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3691 |
return |
| 3692 |
} |
| 3693 |
|
| 3694 |
// We have the stream assigned and a leader, so only the stream leader should answer. |
| 3695 |
if !acc.JetStreamIsStreamLeader(stream) { |
| 3696 |
if js.isLeaderless() { |
| 3697 |
resp.Error = NewJSClusterNotAvailError() |
| 3698 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3699 |
} |
| 3700 |
return |
| 3701 |
} |
| 3702 |
} |
| 3703 |
|
| 3704 |
if errorOnRequiredApiLevel(hdr) { |
| 3705 |
resp.Error = NewJSRequiredApiLevelError() |
| 3706 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3707 |
return |
| 3708 |
} |
| 3709 |
|
| 3710 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3711 |
if doErr { |
| 3712 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3713 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3714 |
} |
| 3715 |
return |
| 3716 |
} |
| 3717 |
|
| 3718 |
var purgeRequest *JSApiStreamPurgeRequest |
| 3719 |
if isJSONObjectOrArray(msg) { |
| 3720 |
var req JSApiStreamPurgeRequest |
| 3721 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 3722 |
resp.Error = NewJSInvalidJSONError(err) |
| 3723 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3724 |
return |
| 3725 |
} |
| 3726 |
if req.Sequence > 0 && req.Keep > 0 { |
| 3727 |
resp.Error = NewJSBadRequestError() |
| 3728 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3729 |
return |
| 3730 |
} |
| 3731 |
purgeRequest = &req |
| 3732 |
} |
| 3733 |
|
| 3734 |
mset, err := acc.lookupStream(stream) |
| 3735 |
if err != nil { |
| 3736 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 3737 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3738 |
return |
| 3739 |
} |
| 3740 |
mset.cfgMu.RLock() |
| 3741 |
sealed, denyPurge := mset.cfg.Sealed, mset.cfg.DenyPurge |
| 3742 |
mset.cfgMu.RUnlock() |
| 3743 |
if sealed { |
| 3744 |
resp.Error = NewJSStreamSealedError() |
| 3745 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3746 |
return |
| 3747 |
} |
| 3748 |
if denyPurge { |
| 3749 |
resp.Error = NewJSStreamPurgeFailedError(errors.New("stream purge not permitted")) |
| 3750 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3751 |
return |
| 3752 |
} |
| 3753 |
|
| 3754 |
if s.JetStreamIsClustered() { |
| 3755 |
s.jsClusteredStreamPurgeRequest(ci, acc, mset, stream, subject, reply, rmsg, purgeRequest) |
| 3756 |
return |
| 3757 |
} |
| 3758 |
|
| 3759 |
purged, err := mset.purge(purgeRequest) |
| 3760 |
if err != nil { |
| 3761 |
resp.Error = NewJSStreamGeneralError(err, Unless(err)) |
| 3762 |
} else { |
| 3763 |
resp.Purged = purged |
| 3764 |
resp.Success = true |
| 3765 |
} |
| 3766 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 3767 |
} |
| 3768 |
|
| 3769 |
func (acc *Account) jsNonClusteredStreamLimitsCheck(cfg *StreamConfig) *ApiError { |
| 3770 |
var replicas int |
| 3771 |
if cfg != nil { |
| 3772 |
replicas = cfg.Replicas |
| 3773 |
} |
| 3774 |
selectedLimits, tier, jsa, apiErr := acc.selectLimits(replicas) |
| 3775 |
if apiErr != nil { |
| 3776 |
return apiErr |
| 3777 |
} |
| 3778 |
jsa.js.mu.RLock() |
| 3779 |
defer jsa.js.mu.RUnlock() |
| 3780 |
jsa.mu.RLock() |
| 3781 |
defer jsa.mu.RUnlock() |
| 3782 |
if selectedLimits.MaxStreams > 0 && jsa.countStreams(tier, cfg) >= selectedLimits.MaxStreams { |
| 3783 |
return NewJSMaximumStreamsLimitError() |
| 3784 |
} |
| 3785 |
reserved := jsa.tieredReservation(tier, cfg) |
| 3786 |
if err := jsa.js.checkAllLimits(selectedLimits, tier, cfg, reserved, 0); err != nil { |
| 3787 |
return NewJSStreamLimitsError(err, Unless(err)) |
| 3788 |
} |
| 3789 |
return nil |
| 3790 |
} |
| 3791 |
|
| 3792 |
// Request to restore a stream. |
| 3793 |
func (s *Server) jsStreamRestoreRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 3794 |
if c == nil || !s.JetStreamIsLeader() { |
| 3795 |
return |
| 3796 |
} |
| 3797 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 3798 |
if err != nil { |
| 3799 |
s.Warnf(badAPIRequestT, msg) |
| 3800 |
return |
| 3801 |
} |
| 3802 |
|
| 3803 |
var resp = JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}} |
| 3804 |
if errorOnRequiredApiLevel(hdr) { |
| 3805 |
resp.Error = NewJSRequiredApiLevelError() |
| 3806 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3807 |
return |
| 3808 |
} |
| 3809 |
if !acc.JetStreamEnabled() { |
| 3810 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3811 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3812 |
return |
| 3813 |
} |
| 3814 |
if isEmptyRequest(msg) { |
| 3815 |
resp.Error = NewJSBadRequestError() |
| 3816 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3817 |
return |
| 3818 |
} |
| 3819 |
|
| 3820 |
var req JSApiStreamRestoreRequest |
| 3821 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 3822 |
resp.Error = NewJSInvalidJSONError(err) |
| 3823 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3824 |
return |
| 3825 |
} |
| 3826 |
|
| 3827 |
stream := streamNameFromSubject(subject) |
| 3828 |
|
| 3829 |
if stream != req.Config.Name && req.Config.Name == _EMPTY_ { |
| 3830 |
req.Config.Name = stream |
| 3831 |
} |
| 3832 |
if stream != req.Config.Name { |
| 3833 |
resp.Error = NewJSStreamMismatchError() |
| 3834 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3835 |
return |
| 3836 |
} |
| 3837 |
|
| 3838 |
// Check for path like separators in the name. |
| 3839 |
if strings.ContainsAny(stream, `\/`) { |
| 3840 |
resp.Error = NewJSStreamNameContainsPathSeparatorsError() |
| 3841 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3842 |
return |
| 3843 |
} |
| 3844 |
|
| 3845 |
if s.JetStreamIsClustered() { |
| 3846 |
s.jsClusteredStreamRestoreRequest(ci, acc, &req, subject, reply, rmsg) |
| 3847 |
return |
| 3848 |
} |
| 3849 |
|
| 3850 |
// check stream config at the start of the restore process, not at the end |
| 3851 |
cfg, apiErr := s.checkStreamCfg(&req.Config, acc, false) |
| 3852 |
if apiErr != nil { |
| 3853 |
resp.Error = apiErr |
| 3854 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3855 |
return |
| 3856 |
} |
| 3857 |
|
| 3858 |
if err := acc.jsNonClusteredStreamLimitsCheck(&cfg); err != nil { |
| 3859 |
resp.Error = err |
| 3860 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3861 |
return |
| 3862 |
} |
| 3863 |
|
| 3864 |
if _, err := acc.lookupStream(stream); err == nil { |
| 3865 |
resp.Error = NewJSStreamNameExistRestoreFailedError() |
| 3866 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3867 |
return |
| 3868 |
} |
| 3869 |
|
| 3870 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 3871 |
if doErr { |
| 3872 |
resp.Error = NewJSNotEnabledForAccountError() |
| 3873 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 3874 |
} |
| 3875 |
return |
| 3876 |
} |
| 3877 |
|
| 3878 |
s.processStreamRestore(ci, acc, &cfg, subject, reply, string(msg)) |
| 3879 |
} |
| 3880 |
|
| 3881 |
func (s *Server) processStreamRestore(ci *ClientInfo, acc *Account, cfg *StreamConfig, subject, reply, msg string) <-chan error { |
| 3882 |
var resp = JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}} |
| 3883 |
|
| 3884 |
streamName := cfg.Name |
| 3885 |
s.Noticef("Starting restore for stream '%s > %s'", acc.Name, streamName) |
| 3886 |
|
| 3887 |
start := time.Now().UTC() |
| 3888 |
domain := s.getOpts().JetStreamDomain |
| 3889 |
s.publishAdvisory(acc, JSAdvisoryStreamRestoreCreatePre+"."+streamName, &JSRestoreCreateAdvisory{ |
| 3890 |
TypedEvent: TypedEvent{ |
| 3891 |
Type: JSRestoreCreateAdvisoryType, |
| 3892 |
ID: nuid.Next(), |
| 3893 |
Time: start, |
| 3894 |
}, |
| 3895 |
Stream: streamName, |
| 3896 |
Client: ci.forAdvisory(), |
| 3897 |
Domain: domain, |
| 3898 |
}) |
| 3899 |
|
| 3900 |
// Create our internal subscription to accept the snapshot. |
| 3901 |
restoreSubj := fmt.Sprintf(jsRestoreDeliverT, streamName, nuid.Next()) |
| 3902 |
|
| 3903 |
type result struct { |
| 3904 |
err error |
| 3905 |
reply string |
| 3906 |
} |
| 3907 |
|
| 3908 |
// For signaling to upper layers. |
| 3909 |
var resultOnce sync.Once |
| 3910 |
var closeOnce sync.Once |
| 3911 |
resultCh := make(chan result, 1) |
| 3912 |
pr, pw := io.Pipe() |
| 3913 |
|
| 3914 |
setResult := func(err error, reply string) { |
| 3915 |
resultOnce.Do(func() { |
| 3916 |
resultCh <- result{err, reply} |
| 3917 |
}) |
| 3918 |
} |
| 3919 |
activeQ := newIPQueue[int](s, fmt.Sprintf("[ACC:%s] stream '%s' restore", acc.Name, streamName)) |
| 3920 |
restoreCh := make(chan struct { |
| 3921 |
mset *stream |
| 3922 |
err error |
| 3923 |
}, 1) |
| 3924 |
closeWithError := func(err error) { |
| 3925 |
closeOnce.Do(func() { |
| 3926 |
if err != nil { |
| 3927 |
pw.CloseWithError(err) |
| 3928 |
} else { |
| 3929 |
pw.Close() |
| 3930 |
} |
| 3931 |
}) |
| 3932 |
} |
| 3933 |
|
| 3934 |
s.startGoRoutine(func() { |
| 3935 |
defer s.grWG.Done() |
| 3936 |
mset, err := acc.RestoreStream(cfg, pr) |
| 3937 |
if err != nil { |
| 3938 |
pr.CloseWithError(err) |
| 3939 |
} else { |
| 3940 |
pr.Close() |
| 3941 |
} |
| 3942 |
restoreCh <- struct { |
| 3943 |
mset *stream |
| 3944 |
err error |
| 3945 |
}{ |
| 3946 |
mset: mset, |
| 3947 |
err: err, |
| 3948 |
} |
| 3949 |
}) |
| 3950 |
|
| 3951 |
processChunk := func(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) { |
| 3952 |
// We require reply subjects to communicate back failures, flow etc. If they do not have one log and cancel. |
| 3953 |
if reply == _EMPTY_ { |
| 3954 |
sub.client.processUnsub(sub.sid) |
| 3955 |
setResult(fmt.Errorf("restore for stream '%s > %s' requires reply subject for each chunk", acc.Name, streamName), reply) |
| 3956 |
return |
| 3957 |
} |
| 3958 |
// Account client messages have \r\n on end. This is an error. |
| 3959 |
if len(msg) < LEN_CR_LF { |
| 3960 |
sub.client.processUnsub(sub.sid) |
| 3961 |
setResult(fmt.Errorf("restore for stream '%s > %s' received short chunk", acc.Name, streamName), reply) |
| 3962 |
return |
| 3963 |
} |
| 3964 |
// Adjust. |
| 3965 |
msg = msg[:len(msg)-LEN_CR_LF] |
| 3966 |
|
| 3967 |
// This means we are complete with our transfer from the client. |
| 3968 |
if len(msg) == 0 { |
| 3969 |
s.Debugf("Finished streaming restore for stream '%s > %s'", acc.Name, streamName) |
| 3970 |
closeWithError(nil) |
| 3971 |
setResult(nil, reply) |
| 3972 |
return |
| 3973 |
} |
| 3974 |
|
| 3975 |
// Signal activity before and after the blocking write. |
| 3976 |
// The pre-write signal refreshes the stall watchdog when the |
| 3977 |
// chunk arrives; the post-write signal refreshes it again once |
| 3978 |
// RestoreStream has consumed the data. This keeps the idle |
| 3979 |
// window between chunks anchored to the end of the previous |
| 3980 |
// write instead of its start. |
| 3981 |
activeQ.push(0) |
| 3982 |
|
| 3983 |
if _, err := pw.Write(msg); err != nil { |
| 3984 |
closeWithError(err) |
| 3985 |
sub.client.processUnsub(sub.sid) |
| 3986 |
var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}} |
| 3987 |
if IsNatsErr(err, JSStorageResourcesExceededErr, JSMemoryResourcesExceededErr) { |
| 3988 |
s.resourcesExceededError(cfg.Storage) |
| 3989 |
} |
| 3990 |
resp.Error = NewJSStreamRestoreError(err, Unless(err)) |
| 3991 |
if s.sendInternalAccountMsg(acc, reply, s.jsonResponse(&resp)) == nil { |
| 3992 |
reply = _EMPTY_ |
| 3993 |
} |
| 3994 |
setResult(err, reply) |
| 3995 |
return |
| 3996 |
} |
| 3997 |
|
| 3998 |
activeQ.push(len(msg)) |
| 3999 |
|
| 4000 |
s.sendInternalAccountMsg(acc, reply, nil) |
| 4001 |
} |
| 4002 |
|
| 4003 |
sub, err := acc.subscribeInternal(restoreSubj, processChunk) |
| 4004 |
if err != nil { |
| 4005 |
closeWithError(err) |
| 4006 |
resp.Error = NewJSRestoreSubscribeFailedError(err, restoreSubj) |
| 4007 |
s.sendAPIErrResponse(ci, acc, subject, reply, msg, s.jsonResponse(&resp)) |
| 4008 |
return nil |
| 4009 |
} |
| 4010 |
|
| 4011 |
// Mark the subject so the end user knows where to send the snapshot chunks. |
| 4012 |
resp.DeliverSubject = restoreSubj |
| 4013 |
s.sendAPIResponse(ci, acc, subject, reply, msg, s.jsonResponse(resp)) |
| 4014 |
|
| 4015 |
// Returned to the caller to wait for completion. |
| 4016 |
doneCh := make(chan error, 1) |
| 4017 |
|
| 4018 |
// Monitor the progress from another Go routine. |
| 4019 |
s.startGoRoutine(func() { |
| 4020 |
defer s.grWG.Done() |
| 4021 |
defer func() { |
| 4022 |
closeWithError(ErrConnectionClosed) |
| 4023 |
sub.client.processUnsub(sub.sid) |
| 4024 |
activeQ.unregister() |
| 4025 |
}() |
| 4026 |
|
| 4027 |
const activityInterval = 5 * time.Second |
| 4028 |
notActive := time.NewTimer(activityInterval) |
| 4029 |
defer notActive.Stop() |
| 4030 |
|
| 4031 |
total := 0 |
| 4032 |
var inputDone bool |
| 4033 |
var replySubj string |
| 4034 |
var inputErr error |
| 4035 |
var restoreDone bool |
| 4036 |
var restoreResult struct { |
| 4037 |
mset *stream |
| 4038 |
err error |
| 4039 |
} |
| 4040 |
|
| 4041 |
finish := func(reply string, err error, mset *stream) { |
| 4042 |
end := time.Now().UTC() |
| 4043 |
|
| 4044 |
s.publishAdvisory(acc, JSAdvisoryStreamRestoreCompletePre+"."+streamName, &JSRestoreCompleteAdvisory{ |
| 4045 |
TypedEvent: TypedEvent{ |
| 4046 |
Type: JSRestoreCompleteAdvisoryType, |
| 4047 |
ID: nuid.Next(), |
| 4048 |
Time: end, |
| 4049 |
}, |
| 4050 |
Stream: streamName, |
| 4051 |
Start: start, |
| 4052 |
End: end, |
| 4053 |
Bytes: int64(total), |
| 4054 |
Client: ci.forAdvisory(), |
| 4055 |
Domain: domain, |
| 4056 |
}) |
| 4057 |
|
| 4058 |
var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}} |
| 4059 |
if err != nil { |
| 4060 |
if IsNatsErr(err, JSStorageResourcesExceededErr, JSMemoryResourcesExceededErr) { |
| 4061 |
s.resourcesExceededError(cfg.Storage) |
| 4062 |
} |
| 4063 |
resp.Error = NewJSStreamRestoreError(err, Unless(err)) |
| 4064 |
s.Warnf("Restore failed for %s for stream '%s > %s' in %v", |
| 4065 |
friendlyBytes(int64(total)), acc.Name, streamName, end.Sub(start)) |
| 4066 |
} else { |
| 4067 |
msetCfg := mset.config() |
| 4068 |
resp.StreamInfo = &StreamInfo{ |
| 4069 |
Created: mset.createdTime(), |
| 4070 |
State: mset.state(), |
| 4071 |
Config: *setDynamicStreamMetadata(&msetCfg), |
| 4072 |
TimeStamp: time.Now().UTC(), |
| 4073 |
} |
| 4074 |
s.Noticef("Completed restore of %s for stream '%s > %s' in %v", |
| 4075 |
friendlyBytes(int64(total)), acc.Name, streamName, end.Sub(start).Round(time.Millisecond)) |
| 4076 |
} |
| 4077 |
if reply != _EMPTY_ { |
| 4078 |
s.sendInternalAccountMsg(acc, reply, s.jsonResponse(&resp)) |
| 4079 |
} |
| 4080 |
doneCh <- err |
| 4081 |
} |
| 4082 |
|
| 4083 |
for { |
| 4084 |
select { |
| 4085 |
case result := <-resultCh: |
| 4086 |
replySubj = result.reply |
| 4087 |
inputDone = true |
| 4088 |
inputErr = result.err |
| 4089 |
notActive.Stop() |
| 4090 |
if result.err != nil { |
| 4091 |
closeWithError(result.err) |
| 4092 |
s.Warnf(result.err.Error()) |
| 4093 |
} |
| 4094 |
if restoreDone { |
| 4095 |
err := inputErr |
| 4096 |
if err == nil { |
| 4097 |
err = restoreResult.err |
| 4098 |
} |
| 4099 |
finish(replySubj, err, restoreResult.mset) |
| 4100 |
return |
| 4101 |
} |
| 4102 |
case rr := <-restoreCh: |
| 4103 |
restoreDone = true |
| 4104 |
restoreResult = rr |
| 4105 |
if inputDone { |
| 4106 |
err := inputErr |
| 4107 |
if err == nil { |
| 4108 |
err = rr.err |
| 4109 |
} |
| 4110 |
finish(replySubj, err, rr.mset) |
| 4111 |
return |
| 4112 |
} |
| 4113 |
case <-activeQ.ch: |
| 4114 |
if n, ok := activeQ.popOne(); ok { |
| 4115 |
total += n |
| 4116 |
if !inputDone { |
| 4117 |
notActive.Reset(activityInterval) |
| 4118 |
} |
| 4119 |
} |
| 4120 |
case <-notActive.C: |
| 4121 |
err := fmt.Errorf("restore for stream '%s > %s' is stalled", acc.Name, streamName) |
| 4122 |
closeWithError(err) |
| 4123 |
doneCh <- err |
| 4124 |
return |
| 4125 |
} |
| 4126 |
} |
| 4127 |
}) |
| 4128 |
|
| 4129 |
return doneCh |
| 4130 |
} |
| 4131 |
|
| 4132 |
// Process a snapshot request. |
| 4133 |
func (s *Server) jsStreamSnapshotRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 4134 |
if c == nil || !s.JetStreamEnabled() { |
| 4135 |
return |
| 4136 |
} |
| 4137 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 4138 |
if err != nil { |
| 4139 |
s.Warnf(badAPIRequestT, msg) |
| 4140 |
return |
| 4141 |
} |
| 4142 |
|
| 4143 |
smsg := string(msg) |
| 4144 |
stream := streamNameFromSubject(subject) |
| 4145 |
|
| 4146 |
// If we are in clustered mode we need to be the stream leader to proceed. |
| 4147 |
if s.JetStreamIsClustered() && !acc.JetStreamIsStreamLeader(stream) { |
| 4148 |
return |
| 4149 |
} |
| 4150 |
|
| 4151 |
var resp = JSApiStreamSnapshotResponse{ApiResponse: ApiResponse{Type: JSApiStreamSnapshotResponseType}} |
| 4152 |
if errorOnRequiredApiLevel(hdr) { |
| 4153 |
resp.Error = NewJSRequiredApiLevelError() |
| 4154 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4155 |
return |
| 4156 |
} |
| 4157 |
if !acc.JetStreamEnabled() { |
| 4158 |
resp.Error = NewJSNotEnabledForAccountError() |
| 4159 |
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp)) |
| 4160 |
return |
| 4161 |
} |
| 4162 |
if isEmptyRequest(msg) { |
| 4163 |
resp.Error = NewJSBadRequestError() |
| 4164 |
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp)) |
| 4165 |
return |
| 4166 |
} |
| 4167 |
|
| 4168 |
mset, err := acc.lookupStream(stream) |
| 4169 |
if err != nil { |
| 4170 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 4171 |
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp)) |
| 4172 |
return |
| 4173 |
} |
| 4174 |
|
| 4175 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 4176 |
if doErr { |
| 4177 |
resp.Error = NewJSNotEnabledForAccountError() |
| 4178 |
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp)) |
| 4179 |
} |
| 4180 |
return |
| 4181 |
} |
| 4182 |
|
| 4183 |
var req JSApiStreamSnapshotRequest |
| 4184 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 4185 |
resp.Error = NewJSInvalidJSONError(err) |
| 4186 |
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp)) |
| 4187 |
return |
| 4188 |
} |
| 4189 |
if !IsValidPublishSubject(req.DeliverSubject) { |
| 4190 |
resp.Error = NewJSSnapshotDeliverSubjectInvalidError() |
| 4191 |
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp)) |
| 4192 |
return |
| 4193 |
} |
| 4194 |
|
| 4195 |
// We will do the snapshot in a go routine as well since check msgs may |
| 4196 |
// stall this go routine. |
| 4197 |
go func() { |
| 4198 |
if req.CheckMsgs { |
| 4199 |
s.Noticef("Starting health check and snapshot for stream '%s > %s'", mset.jsa.account.Name, mset.name()) |
| 4200 |
} else { |
| 4201 |
s.Noticef("Starting snapshot for stream '%s > %s'", mset.jsa.account.Name, mset.name()) |
| 4202 |
} |
| 4203 |
|
| 4204 |
start := time.Now().UTC() |
| 4205 |
|
| 4206 |
sr, err := mset.snapshot(0, req.CheckMsgs, !req.NoConsumers) |
| 4207 |
if err != nil { |
| 4208 |
s.Warnf("Snapshot of stream '%s > %s' failed: %v", mset.jsa.account.Name, mset.name(), err) |
| 4209 |
resp.Error = NewJSStreamSnapshotError(err, Unless(err)) |
| 4210 |
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp)) |
| 4211 |
return |
| 4212 |
} |
| 4213 |
|
| 4214 |
config := mset.config() |
| 4215 |
resp.State = &sr.State |
| 4216 |
resp.Config = &config |
| 4217 |
|
| 4218 |
s.sendAPIResponse(ci, acc, subject, reply, smsg, s.jsonResponse(resp)) |
| 4219 |
|
| 4220 |
s.publishAdvisory(acc, JSAdvisoryStreamSnapshotCreatePre+"."+mset.name(), &JSSnapshotCreateAdvisory{ |
| 4221 |
TypedEvent: TypedEvent{ |
| 4222 |
Type: JSSnapshotCreatedAdvisoryType, |
| 4223 |
ID: nuid.Next(), |
| 4224 |
Time: time.Now().UTC(), |
| 4225 |
}, |
| 4226 |
Stream: mset.name(), |
| 4227 |
State: sr.State, |
| 4228 |
Client: ci.forAdvisory(), |
| 4229 |
Domain: s.getOpts().JetStreamDomain, |
| 4230 |
}) |
| 4231 |
|
| 4232 |
// Now do the real streaming. |
| 4233 |
if err := s.streamSnapshot(acc, mset, sr, &req); err != nil { |
| 4234 |
s.Warnf("Snapshot of stream '%s > %s' failed: %v", mset.jsa.account.Name, mset.name(), err) |
| 4235 |
return |
| 4236 |
} |
| 4237 |
|
| 4238 |
end := time.Now().UTC() |
| 4239 |
|
| 4240 |
s.publishAdvisory(acc, JSAdvisoryStreamSnapshotCompletePre+"."+mset.name(), &JSSnapshotCompleteAdvisory{ |
| 4241 |
TypedEvent: TypedEvent{ |
| 4242 |
Type: JSSnapshotCompleteAdvisoryType, |
| 4243 |
ID: nuid.Next(), |
| 4244 |
Time: end, |
| 4245 |
}, |
| 4246 |
Stream: mset.name(), |
| 4247 |
Start: start, |
| 4248 |
End: end, |
| 4249 |
Client: ci.forAdvisory(), |
| 4250 |
Domain: s.getOpts().JetStreamDomain, |
| 4251 |
}) |
| 4252 |
|
| 4253 |
s.Noticef("Completed snapshot of %s for stream '%s > %s' in %v", |
| 4254 |
friendlyBytes(int64(sr.State.Bytes)), |
| 4255 |
mset.jsa.account.Name, |
| 4256 |
mset.name(), |
| 4257 |
end.Sub(start)) |
| 4258 |
}() |
| 4259 |
} |
| 4260 |
|
| 4261 |
// Default chunk size for now. |
| 4262 |
const defaultSnapshotChunkSize = 128 * 1024 // 128KiB |
| 4263 |
const defaultSnapshotWindowSize = 8 * 1024 * 1024 // 8MiB |
| 4264 |
const defaultSnapshotAckTimeout = 5 * time.Second |
| 4265 |
|
| 4266 |
var snapshotAckTimeout = defaultSnapshotAckTimeout |
| 4267 |
|
| 4268 |
// streamSnapshot will stream out our snapshot to the reply subject. |
| 4269 |
func (s *Server) streamSnapshot(acc *Account, mset *stream, sr *SnapshotResult, req *JSApiStreamSnapshotRequest) error { |
| 4270 |
chunkSize, wndSize := req.ChunkSize, req.WindowSize |
| 4271 |
if chunkSize == 0 { |
| 4272 |
chunkSize = defaultSnapshotChunkSize |
| 4273 |
} |
| 4274 |
if wndSize == 0 { |
| 4275 |
wndSize = defaultSnapshotWindowSize |
| 4276 |
} |
| 4277 |
chunkSize = min(max(1024, chunkSize), 1024*1024) // Clamp within 1KiB to 1MiB |
| 4278 |
wndSize = min(max(1024, wndSize), 32*1024*1024) // Clamp within 1KiB to 32MiB |
| 4279 |
wndSize = max(wndSize, chunkSize) // Guarantee at least one chunk |
| 4280 |
maxInflight := wndSize / chunkSize // Between 1 and 32,768 |
| 4281 |
|
| 4282 |
// Setup for the chunk stream. |
| 4283 |
reply := req.DeliverSubject |
| 4284 |
r := sr.Reader |
| 4285 |
defer r.Close() |
| 4286 |
|
| 4287 |
// In case we run into an error, this allows subscription callbacks |
| 4288 |
// to not sit and block endlessly. |
| 4289 |
done := make(chan struct{}) |
| 4290 |
defer close(done) |
| 4291 |
|
| 4292 |
// Check interest for the snapshot deliver subject. |
| 4293 |
inch := make(chan bool, 1) |
| 4294 |
if err := acc.sl.RegisterNotification(req.DeliverSubject, inch); err != nil { |
| 4295 |
return fmt.Errorf("could not register snapshot delivery interest for %q: %w", req.DeliverSubject, err) |
| 4296 |
} |
| 4297 |
defer acc.sl.ClearNotification(req.DeliverSubject, inch) |
| 4298 |
hasInterest := <-inch |
| 4299 |
if !hasInterest { |
| 4300 |
// Allow 2 seconds or so for interest to show up. |
| 4301 |
select { |
| 4302 |
case <-inch: |
| 4303 |
case <-time.After(2 * time.Second): |
| 4304 |
} |
| 4305 |
} |
| 4306 |
|
| 4307 |
// One slot per chunk. Each chunk read takes a slot, each ack will |
| 4308 |
// replace it. Smooths out in-flight number of chunks. |
| 4309 |
slots := make(chan struct{}, maxInflight) |
| 4310 |
for range maxInflight { |
| 4311 |
slots <- struct{}{} |
| 4312 |
} |
| 4313 |
|
| 4314 |
// We will place sequence number and size of chunk sent in the reply. |
| 4315 |
ackSubj := fmt.Sprintf(jsSnapshotAckT, mset.name(), nuid.Next()) |
| 4316 |
ackSub, _ := mset.subscribeInternal(ackSubj+".>", func(_ *subscription, _ *client, _ *Account, subject, _ string, _ []byte) { |
| 4317 |
select { |
| 4318 |
case slots <- struct{}{}: |
| 4319 |
case <-done: |
| 4320 |
} |
| 4321 |
}) |
| 4322 |
defer mset.unsubscribe(ackSub) |
| 4323 |
|
| 4324 |
var hdr []byte |
| 4325 |
chunk := make([]byte, chunkSize) |
| 4326 |
ackTimer := time.NewTimer(snapshotAckTimeout) |
| 4327 |
defer stopAndClearTimer(&ackTimer) |
| 4328 |
for index := 1; ; index++ { |
| 4329 |
select { |
| 4330 |
case <-slots: |
| 4331 |
// A slot has become available. |
| 4332 |
case <-inch: |
| 4333 |
// The receiver appears to have gone away. |
| 4334 |
hdr = []byte("NATS/1.0 408 No Interest\r\n\r\n") |
| 4335 |
goto done |
| 4336 |
case err := <-sr.errCh: |
| 4337 |
// The snapshotting goroutine has failed for some reason. |
| 4338 |
hdr = []byte(fmt.Sprintf("NATS/1.0 500 %s\r\n\r\n", err)) |
| 4339 |
goto done |
| 4340 |
case <-ackTimer.C: |
| 4341 |
// It's taking a very long time for the receiver to send us acks, |
| 4342 |
// they have probably stalled or there is high loss on the link. |
| 4343 |
hdr = []byte("NATS/1.0 408 No Flow Response\r\n\r\n") |
| 4344 |
goto done |
| 4345 |
} |
| 4346 |
n, err := io.ReadFull(r, chunk) |
| 4347 |
chunk := chunk[:n] |
| 4348 |
if err != nil { |
| 4349 |
if n > 0 { |
| 4350 |
mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, nil, chunk, nil, 0)) |
| 4351 |
} |
| 4352 |
break |
| 4353 |
} |
| 4354 |
ackReply := fmt.Sprintf("%s.%d.%d", ackSubj, len(chunk), index) |
| 4355 |
if hdr == nil { |
| 4356 |
hdr = []byte("NATS/1.0 204\r\n\r\n") |
| 4357 |
} |
| 4358 |
mset.outq.send(newJSPubMsg(reply, _EMPTY_, ackReply, nil, chunk, nil, 0)) |
| 4359 |
ackTimer.Reset(snapshotAckTimeout) |
| 4360 |
} |
| 4361 |
|
| 4362 |
done: |
| 4363 |
mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0)) |
| 4364 |
return nil |
| 4365 |
} |
| 4366 |
|
| 4367 |
// For determining consumer request type. |
| 4368 |
type ccReqType uint8 |
| 4369 |
|
| 4370 |
const ( |
| 4371 |
ccNew = iota |
| 4372 |
ccLegacyEphemeral |
| 4373 |
ccLegacyDurable |
| 4374 |
) |
| 4375 |
|
| 4376 |
// Request to create a consumer where stream and optional consumer name are part of the subject, and optional |
| 4377 |
// filtered subjects can be at the tail end. |
| 4378 |
// Assumes stream and consumer names are single tokens. |
| 4379 |
func (s *Server) jsConsumerCreateRequest(sub *subscription, c *client, a *Account, subject, reply string, rmsg []byte) { |
| 4380 |
if c == nil || !s.JetStreamEnabled() { |
| 4381 |
return |
| 4382 |
} |
| 4383 |
|
| 4384 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 4385 |
if err != nil { |
| 4386 |
s.Warnf(badAPIRequestT, msg) |
| 4387 |
return |
| 4388 |
} |
| 4389 |
|
| 4390 |
var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}} |
| 4391 |
|
| 4392 |
var req CreateConsumerRequest |
| 4393 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 4394 |
resp.Error = NewJSInvalidJSONError(err) |
| 4395 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4396 |
return |
| 4397 |
} |
| 4398 |
|
| 4399 |
var js *jetStream |
| 4400 |
isClustered := s.JetStreamIsClustered() |
| 4401 |
|
| 4402 |
// Determine if we should proceed here when we are in clustered mode. |
| 4403 |
direct := req.Config.Direct |
| 4404 |
if isClustered { |
| 4405 |
if direct { |
| 4406 |
// If it's just a direct consumer, check for stream leader. |
| 4407 |
if !req.Config.Sourcing { |
| 4408 |
// Check to see if we have this stream and are the stream leader. |
| 4409 |
if !acc.JetStreamIsStreamLeader(streamNameFromSubject(subject)) { |
| 4410 |
return |
| 4411 |
} |
| 4412 |
} else { |
| 4413 |
// Otherwise, we either need this to be answered by the stream or meta leader. |
| 4414 |
var cc *jetStreamCluster |
| 4415 |
js, cc = s.getJetStreamCluster() |
| 4416 |
if js == nil || cc == nil { |
| 4417 |
return |
| 4418 |
} |
| 4419 |
js.mu.RLock() |
| 4420 |
sa := js.streamAssignmentOrInflight(acc.Name, streamNameFromSubject(subject)) |
| 4421 |
if sa == nil { |
| 4422 |
js.mu.RUnlock() |
| 4423 |
return |
| 4424 |
} |
| 4425 |
// If the stream is WQ or Interest, we need the meta leader to answer. |
| 4426 |
if sa.Config.Retention != LimitsPolicy { |
| 4427 |
direct = false |
| 4428 |
} |
| 4429 |
js.mu.RUnlock() |
| 4430 |
if direct { |
| 4431 |
// Check to see if we have this stream and are the stream leader. |
| 4432 |
if !acc.JetStreamIsStreamLeader(streamNameFromSubject(subject)) { |
| 4433 |
return |
| 4434 |
} |
| 4435 |
} else { |
| 4436 |
if js.isLeaderless() { |
| 4437 |
resp.Error = NewJSClusterNotAvailError() |
| 4438 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4439 |
return |
| 4440 |
} |
| 4441 |
// Make sure we are meta leader. |
| 4442 |
if !s.JetStreamIsLeader() { |
| 4443 |
return |
| 4444 |
} |
| 4445 |
} |
| 4446 |
} |
| 4447 |
} else { |
| 4448 |
var cc *jetStreamCluster |
| 4449 |
js, cc = s.getJetStreamCluster() |
| 4450 |
if js == nil || cc == nil { |
| 4451 |
return |
| 4452 |
} |
| 4453 |
if js.isLeaderless() { |
| 4454 |
resp.Error = NewJSClusterNotAvailError() |
| 4455 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4456 |
return |
| 4457 |
} |
| 4458 |
// Make sure we are meta leader. |
| 4459 |
if !s.JetStreamIsLeader() { |
| 4460 |
return |
| 4461 |
} |
| 4462 |
} |
| 4463 |
} |
| 4464 |
|
| 4465 |
if errorOnRequiredApiLevel(hdr) { |
| 4466 |
resp.Error = NewJSRequiredApiLevelError() |
| 4467 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4468 |
return |
| 4469 |
} |
| 4470 |
|
| 4471 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 4472 |
if doErr { |
| 4473 |
resp.Error = NewJSNotEnabledForAccountError() |
| 4474 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4475 |
} |
| 4476 |
return |
| 4477 |
} |
| 4478 |
|
| 4479 |
var streamName, consumerName, filteredSubject string |
| 4480 |
var rt ccReqType |
| 4481 |
|
| 4482 |
if n := numTokens(subject); n < 5 { |
| 4483 |
s.Warnf(badAPIRequestT, msg) |
| 4484 |
return |
| 4485 |
} else if n == 5 { |
| 4486 |
// Legacy ephemeral. |
| 4487 |
rt = ccLegacyEphemeral |
| 4488 |
streamName = streamNameFromSubject(subject) |
| 4489 |
consumerName = req.Config.Name |
| 4490 |
} else { |
| 4491 |
// New style and durable legacy. |
| 4492 |
if tokenAt(subject, 4) == "DURABLE" { |
| 4493 |
rt = ccLegacyDurable |
| 4494 |
if n != 7 { |
| 4495 |
resp.Error = NewJSConsumerDurableNameNotInSubjectError() |
| 4496 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4497 |
return |
| 4498 |
} |
| 4499 |
streamName = tokenAt(subject, 6) |
| 4500 |
consumerName = tokenAt(subject, 7) |
| 4501 |
} else { |
| 4502 |
streamName = streamNameFromSubject(subject) |
| 4503 |
consumerName = consumerNameFromSubject(subject) |
| 4504 |
// New has optional filtered subject as part of main subject.. |
| 4505 |
if n > 6 { |
| 4506 |
tokens := strings.Split(subject, tsep) |
| 4507 |
filteredSubject = strings.Join(tokens[6:], tsep) |
| 4508 |
} |
| 4509 |
} |
| 4510 |
} |
| 4511 |
|
| 4512 |
if streamName != req.Stream { |
| 4513 |
resp.Error = NewJSStreamMismatchError() |
| 4514 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4515 |
return |
| 4516 |
} |
| 4517 |
|
| 4518 |
if consumerName != _EMPTY_ { |
| 4519 |
// Check for path like separators in the name. |
| 4520 |
if strings.ContainsAny(consumerName, `\/`) { |
| 4521 |
resp.Error = NewJSConsumerNameContainsPathSeparatorsError() |
| 4522 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4523 |
return |
| 4524 |
} |
| 4525 |
} |
| 4526 |
|
| 4527 |
// Should we expect a durable name |
| 4528 |
if rt == ccLegacyDurable { |
| 4529 |
if numTokens(subject) < 7 { |
| 4530 |
resp.Error = NewJSConsumerDurableNameNotInSubjectError() |
| 4531 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4532 |
return |
| 4533 |
} |
| 4534 |
// Now check on requirements for durable request. |
| 4535 |
if req.Config.Durable == _EMPTY_ { |
| 4536 |
resp.Error = NewJSConsumerDurableNameNotSetError() |
| 4537 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4538 |
return |
| 4539 |
} |
| 4540 |
if consumerName != req.Config.Durable { |
| 4541 |
resp.Error = NewJSConsumerDurableNameNotMatchSubjectError() |
| 4542 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4543 |
return |
| 4544 |
} |
| 4545 |
// Durable, so we need to honor the name. |
| 4546 |
req.Config.Name = consumerName |
| 4547 |
} |
| 4548 |
// If new style and durable set make sure they match. |
| 4549 |
if rt == ccNew { |
| 4550 |
if req.Config.Durable != _EMPTY_ { |
| 4551 |
if consumerName != req.Config.Durable { |
| 4552 |
resp.Error = NewJSConsumerDurableNameNotMatchSubjectError() |
| 4553 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4554 |
return |
| 4555 |
} |
| 4556 |
} |
| 4557 |
// New style ephemeral so we need to honor the name. |
| 4558 |
req.Config.Name = consumerName |
| 4559 |
} |
| 4560 |
// Check for legacy ephemeral mis-configuration. |
| 4561 |
if rt == ccLegacyEphemeral && req.Config.Durable != _EMPTY_ { |
| 4562 |
resp.Error = NewJSConsumerEphemeralWithDurableNameError() |
| 4563 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4564 |
return |
| 4565 |
} |
| 4566 |
|
| 4567 |
// in case of multiple filters provided, error if new API is used. |
| 4568 |
if filteredSubject != _EMPTY_ && len(req.Config.FilterSubjects) != 0 { |
| 4569 |
resp.Error = NewJSConsumerMultipleFiltersNotAllowedError() |
| 4570 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4571 |
return |
| 4572 |
} |
| 4573 |
|
| 4574 |
// Check for a filter subject. |
| 4575 |
if filteredSubject != _EMPTY_ && req.Config.FilterSubject != filteredSubject { |
| 4576 |
resp.Error = NewJSConsumerCreateFilterSubjectMismatchError() |
| 4577 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4578 |
return |
| 4579 |
} |
| 4580 |
|
| 4581 |
if isClustered && !direct { |
| 4582 |
s.jsClusteredConsumerRequest(ci, acc, subject, reply, rmsg, req.Stream, &req.Config, req.Action, req.Pedantic) |
| 4583 |
return |
| 4584 |
} |
| 4585 |
|
| 4586 |
// If we are here we are single server mode. |
| 4587 |
if req.Config.Replicas > 1 { |
| 4588 |
resp.Error = NewJSStreamReplicasNotSupportedError() |
| 4589 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4590 |
return |
| 4591 |
} |
| 4592 |
|
| 4593 |
stream, err := acc.lookupStream(req.Stream) |
| 4594 |
if err != nil { |
| 4595 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 4596 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4597 |
return |
| 4598 |
} |
| 4599 |
if stream.offlineReason != _EMPTY_ { |
| 4600 |
resp.Error = NewJSStreamOfflineReasonError(errors.New(stream.offlineReason)) |
| 4601 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 4602 |
return |
| 4603 |
} |
| 4604 |
|
| 4605 |
// If the consumer is a direct sourcing consumer, we need to "upgrade" |
| 4606 |
// it to be durable without AckNone if not a Limits-based stream. |
| 4607 |
if req.Config.Direct && req.Config.Sourcing && req.Config.Name != _EMPTY_ { |
| 4608 |
if !isClustered && stream.isInterestRetention() { |
| 4609 |
req.Config.Direct = false |
| 4610 |
req.Config.Durable = req.Config.Name |
| 4611 |
req.Config.AckPolicy = AckFlowControl |
| 4612 |
req.Config.AckWait = 0 |
| 4613 |
req.Config.MaxDeliver = 0 |
| 4614 |
req.Config.InactiveThreshold = 0 |
| 4615 |
} else { |
| 4616 |
// Otherwise, need to append a randomized suffix since the source uses a stable name. |
| 4617 |
req.Config.Name = fmt.Sprintf("%s-%s", req.Config.Name, createConsumerName()) |
| 4618 |
consumerName = req.Config.Name |
| 4619 |
} |
| 4620 |
} |
| 4621 |
|
| 4622 |
if o := stream.lookupConsumer(consumerName); o != nil { |
| 4623 |
if o.offlineReason != _EMPTY_ { |
| 4624 |
resp.Error = NewJSConsumerOfflineReasonError(errors.New(o.offlineReason)) |
| 4625 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 4626 |
return |
| 4627 |
} |
| 4628 |
// If the consumer already exists then don't allow updating the PauseUntil, just set |
| 4629 |
// it back to whatever the current configured value is. |
| 4630 |
o.mu.RLock() |
| 4631 |
req.Config.PauseUntil = o.cfg.PauseUntil |
| 4632 |
// If a durable sourcing consumer is used, we need to reset the deliver policy. |
| 4633 |
if req.Config.Sourcing && req.Config.Durable != _EMPTY_ { |
| 4634 |
req.Config.DeliverPolicy = o.cfg.DeliverPolicy |
| 4635 |
req.Config.OptStartSeq = o.cfg.OptStartSeq |
| 4636 |
req.Config.OptStartTime = o.cfg.OptStartTime |
| 4637 |
} |
| 4638 |
o.mu.RUnlock() |
| 4639 |
} |
| 4640 |
|
| 4641 |
// Initialize/update asset version metadata. |
| 4642 |
setStaticConsumerMetadata(&req.Config) |
| 4643 |
|
| 4644 |
o, err := stream.addConsumerWithAction(&req.Config, req.Action, req.Pedantic) |
| 4645 |
|
| 4646 |
if err != nil { |
| 4647 |
if IsNatsErr(err, JSConsumerStoreFailedErrF) { |
| 4648 |
cname := req.Config.Durable // Will be empty if ephemeral. |
| 4649 |
s.Warnf("Consumer create failed for '%s > %s > %s': %v", acc, req.Stream, cname, err) |
| 4650 |
err = errConsumerStoreFailed |
| 4651 |
} |
| 4652 |
resp.Error = NewJSConsumerCreateError(err, Unless(err)) |
| 4653 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4654 |
return |
| 4655 |
} |
| 4656 |
resp.ConsumerInfo = setDynamicConsumerInfoMetadata(o.initialInfo()) |
| 4657 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 4658 |
|
| 4659 |
o.mu.RLock() |
| 4660 |
if o.cfg.PauseUntil != nil && !o.cfg.PauseUntil.IsZero() && time.Now().Before(*o.cfg.PauseUntil) { |
| 4661 |
o.sendPauseAdvisoryLocked(&o.cfg) |
| 4662 |
} |
| 4663 |
o.mu.RUnlock() |
| 4664 |
} |
| 4665 |
|
| 4666 |
// Request for the list of all consumer names. |
| 4667 |
func (s *Server) jsConsumerNamesRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 4668 |
if c == nil || !s.JetStreamEnabled() { |
| 4669 |
return |
| 4670 |
} |
| 4671 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 4672 |
if err != nil { |
| 4673 |
s.Warnf(badAPIRequestT, msg) |
| 4674 |
return |
| 4675 |
} |
| 4676 |
|
| 4677 |
var resp = JSApiConsumerNamesResponse{ |
| 4678 |
ApiResponse: ApiResponse{Type: JSApiConsumerNamesResponseType}, |
| 4679 |
Consumers: []string{}, |
| 4680 |
} |
| 4681 |
|
| 4682 |
// Determine if we should proceed here when we are in clustered mode. |
| 4683 |
if s.JetStreamIsClustered() { |
| 4684 |
js, cc := s.getJetStreamCluster() |
| 4685 |
if js == nil || cc == nil { |
| 4686 |
return |
| 4687 |
} |
| 4688 |
if js.isLeaderless() { |
| 4689 |
resp.Error = NewJSClusterNotAvailError() |
| 4690 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4691 |
return |
| 4692 |
} |
| 4693 |
// Make sure we are meta leader. |
| 4694 |
if !s.JetStreamIsLeader() { |
| 4695 |
return |
| 4696 |
} |
| 4697 |
} |
| 4698 |
|
| 4699 |
if errorOnRequiredApiLevel(hdr) { |
| 4700 |
resp.Error = NewJSRequiredApiLevelError() |
| 4701 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4702 |
return |
| 4703 |
} |
| 4704 |
|
| 4705 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 4706 |
if doErr { |
| 4707 |
resp.Error = NewJSNotEnabledForAccountError() |
| 4708 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4709 |
} |
| 4710 |
return |
| 4711 |
} |
| 4712 |
|
| 4713 |
var offset int |
| 4714 |
if isJSONObjectOrArray(msg) { |
| 4715 |
var req JSApiConsumersRequest |
| 4716 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 4717 |
resp.Error = NewJSInvalidJSONError(err) |
| 4718 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4719 |
return |
| 4720 |
} |
| 4721 |
offset = max(req.Offset, 0) |
| 4722 |
} |
| 4723 |
|
| 4724 |
streamName := streamNameFromSubject(subject) |
| 4725 |
var numConsumers int |
| 4726 |
|
| 4727 |
if s.JetStreamIsClustered() { |
| 4728 |
js, cc := s.getJetStreamCluster() |
| 4729 |
if js == nil || cc == nil { |
| 4730 |
// TODO(dlc) - Debug or Warn? |
| 4731 |
return |
| 4732 |
} |
| 4733 |
js.mu.RLock() |
| 4734 |
sas := cc.streams[acc.Name] |
| 4735 |
if sas == nil { |
| 4736 |
js.mu.RUnlock() |
| 4737 |
resp.Error = NewJSStreamNotFoundError() |
| 4738 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4739 |
return |
| 4740 |
} |
| 4741 |
sa := sas[streamName] |
| 4742 |
if sa == nil || sa.err != nil { |
| 4743 |
js.mu.RUnlock() |
| 4744 |
resp.Error = NewJSStreamNotFoundError() |
| 4745 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4746 |
return |
| 4747 |
} |
| 4748 |
for consumer := range sa.consumers { |
| 4749 |
resp.Consumers = append(resp.Consumers, consumer) |
| 4750 |
} |
| 4751 |
if len(resp.Consumers) > 1 { |
| 4752 |
slices.Sort(resp.Consumers) |
| 4753 |
} |
| 4754 |
numConsumers = len(resp.Consumers) |
| 4755 |
if offset > numConsumers { |
| 4756 |
offset = numConsumers |
| 4757 |
} |
| 4758 |
resp.Consumers = resp.Consumers[offset:] |
| 4759 |
if len(resp.Consumers) > JSApiNamesLimit { |
| 4760 |
resp.Consumers = resp.Consumers[:JSApiNamesLimit] |
| 4761 |
} |
| 4762 |
js.mu.RUnlock() |
| 4763 |
|
| 4764 |
} else { |
| 4765 |
mset, err := acc.lookupStream(streamName) |
| 4766 |
if err != nil { |
| 4767 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 4768 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4769 |
return |
| 4770 |
} |
| 4771 |
|
| 4772 |
obs := mset.getPublicConsumers() |
| 4773 |
slices.SortFunc(obs, func(i, j *consumer) int { return cmp.Compare(i.name, j.name) }) |
| 4774 |
|
| 4775 |
numConsumers = len(obs) |
| 4776 |
if offset > numConsumers { |
| 4777 |
offset = numConsumers |
| 4778 |
} |
| 4779 |
|
| 4780 |
for _, o := range obs[offset:] { |
| 4781 |
resp.Consumers = append(resp.Consumers, o.String()) |
| 4782 |
if len(resp.Consumers) >= JSApiNamesLimit { |
| 4783 |
break |
| 4784 |
} |
| 4785 |
} |
| 4786 |
} |
| 4787 |
resp.Total = numConsumers |
| 4788 |
resp.Limit = JSApiNamesLimit |
| 4789 |
resp.Offset = offset |
| 4790 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 4791 |
} |
| 4792 |
|
| 4793 |
// Request for the list of all detailed consumer information. |
| 4794 |
func (s *Server) jsConsumerListRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 4795 |
if c == nil || !s.JetStreamEnabled() { |
| 4796 |
return |
| 4797 |
} |
| 4798 |
|
| 4799 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 4800 |
if err != nil { |
| 4801 |
s.Warnf(badAPIRequestT, msg) |
| 4802 |
return |
| 4803 |
} |
| 4804 |
|
| 4805 |
var resp = JSApiConsumerListResponse{ |
| 4806 |
ApiResponse: ApiResponse{Type: JSApiConsumerListResponseType}, |
| 4807 |
Consumers: []*ConsumerInfo{}, |
| 4808 |
} |
| 4809 |
|
| 4810 |
// Determine if we should proceed here when we are in clustered mode. |
| 4811 |
if s.JetStreamIsClustered() { |
| 4812 |
js, cc := s.getJetStreamCluster() |
| 4813 |
if js == nil || cc == nil { |
| 4814 |
return |
| 4815 |
} |
| 4816 |
if js.isLeaderless() { |
| 4817 |
resp.Error = NewJSClusterNotAvailError() |
| 4818 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4819 |
return |
| 4820 |
} |
| 4821 |
// Make sure we are meta leader. |
| 4822 |
if !s.JetStreamIsLeader() { |
| 4823 |
return |
| 4824 |
} |
| 4825 |
} |
| 4826 |
|
| 4827 |
if errorOnRequiredApiLevel(hdr) { |
| 4828 |
resp.Error = NewJSRequiredApiLevelError() |
| 4829 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4830 |
return |
| 4831 |
} |
| 4832 |
|
| 4833 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 4834 |
if doErr { |
| 4835 |
resp.Error = NewJSNotEnabledForAccountError() |
| 4836 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4837 |
} |
| 4838 |
return |
| 4839 |
} |
| 4840 |
|
| 4841 |
var offset int |
| 4842 |
if isJSONObjectOrArray(msg) { |
| 4843 |
var req JSApiConsumersRequest |
| 4844 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 4845 |
resp.Error = NewJSInvalidJSONError(err) |
| 4846 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4847 |
return |
| 4848 |
} |
| 4849 |
offset = max(req.Offset, 0) |
| 4850 |
} |
| 4851 |
|
| 4852 |
streamName := streamNameFromSubject(subject) |
| 4853 |
|
| 4854 |
// Clustered mode will invoke a scatter and gather. |
| 4855 |
if s.JetStreamIsClustered() { |
| 4856 |
// Need to copy these off before sending.. don't move this inside startGoRoutine!!! |
| 4857 |
msg = copyBytes(msg) |
| 4858 |
s.startGoRoutine(func() { |
| 4859 |
s.jsClusteredConsumerListRequest(acc, ci, offset, streamName, subject, reply, msg) |
| 4860 |
}) |
| 4861 |
return |
| 4862 |
} |
| 4863 |
|
| 4864 |
mset, err := acc.lookupStream(streamName) |
| 4865 |
if err != nil { |
| 4866 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 4867 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4868 |
return |
| 4869 |
} |
| 4870 |
|
| 4871 |
obs := mset.getPublicConsumers() |
| 4872 |
slices.SortFunc(obs, func(i, j *consumer) int { return cmp.Compare(i.name, j.name) }) |
| 4873 |
|
| 4874 |
ocnt := len(obs) |
| 4875 |
if offset > ocnt { |
| 4876 |
offset = ocnt |
| 4877 |
} |
| 4878 |
|
| 4879 |
var missingNames []string |
| 4880 |
for _, o := range obs[offset:] { |
| 4881 |
if o.offlineReason != _EMPTY_ { |
| 4882 |
if resp.Offline == nil { |
| 4883 |
resp.Offline = make(map[string]string, 1) |
| 4884 |
} |
| 4885 |
resp.Offline[o.name] = o.offlineReason |
| 4886 |
missingNames = append(missingNames, o.name) |
| 4887 |
continue |
| 4888 |
} |
| 4889 |
if cinfo := o.info(); cinfo != nil { |
| 4890 |
resp.Consumers = append(resp.Consumers, cinfo) |
| 4891 |
} |
| 4892 |
if len(resp.Consumers) >= JSApiListLimit { |
| 4893 |
break |
| 4894 |
} |
| 4895 |
} |
| 4896 |
resp.Total = ocnt |
| 4897 |
resp.Limit = JSApiListLimit |
| 4898 |
resp.Offset = offset |
| 4899 |
resp.Missing = missingNames |
| 4900 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 4901 |
} |
| 4902 |
|
| 4903 |
// Request for information about an consumer. |
| 4904 |
func (s *Server) jsConsumerInfoRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 4905 |
if c == nil || !s.JetStreamEnabled() { |
| 4906 |
return |
| 4907 |
} |
| 4908 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 4909 |
if err != nil { |
| 4910 |
s.Warnf(badAPIRequestT, msg) |
| 4911 |
return |
| 4912 |
} |
| 4913 |
|
| 4914 |
streamName := streamNameFromSubject(subject) |
| 4915 |
consumerName := consumerNameFromSubject(subject) |
| 4916 |
|
| 4917 |
var resp = JSApiConsumerInfoResponse{ApiResponse: ApiResponse{Type: JSApiConsumerInfoResponseType}} |
| 4918 |
|
| 4919 |
if !isEmptyRequest(msg) { |
| 4920 |
resp.Error = NewJSNotEmptyRequestError() |
| 4921 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4922 |
return |
| 4923 |
} |
| 4924 |
|
| 4925 |
// If we are in clustered mode we need to be the consumer leader to proceed. |
| 4926 |
if s.JetStreamIsClustered() { |
| 4927 |
// Check to make sure the consumer is assigned. |
| 4928 |
js, cc := s.getJetStreamCluster() |
| 4929 |
if js == nil || cc == nil { |
| 4930 |
return |
| 4931 |
} |
| 4932 |
|
| 4933 |
js.mu.RLock() |
| 4934 |
meta := cc.meta |
| 4935 |
js.mu.RUnlock() |
| 4936 |
|
| 4937 |
if meta == nil { |
| 4938 |
return |
| 4939 |
} |
| 4940 |
|
| 4941 |
// Since these could wait on the Raft group lock, don't do so under the JS lock. |
| 4942 |
ourID := meta.ID() |
| 4943 |
groupLeaderless := meta.Leaderless() |
| 4944 |
groupCreated := meta.Created() |
| 4945 |
|
| 4946 |
js.mu.RLock() |
| 4947 |
isLeader, sa, ca := cc.isLeader(), js.streamAssignmentOrInflight(acc.Name, streamName), js.consumerAssignmentOrInflight(acc.Name, streamName, consumerName) |
| 4948 |
var rg *raftGroup |
| 4949 |
var offline, isMember bool |
| 4950 |
if ca != nil { |
| 4951 |
if rg = ca.Group; rg != nil { |
| 4952 |
offline = s.allPeersOffline(rg) |
| 4953 |
isMember = rg.isMember(ourID) |
| 4954 |
} |
| 4955 |
if ca.unsupported != nil && isMember { |
| 4956 |
// If we're a member for this consumer, and it's not supported, report it as offline. |
| 4957 |
resp.Error = NewJSConsumerOfflineReasonError(errors.New(ca.unsupported.reason)) |
| 4958 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 4959 |
js.mu.RUnlock() |
| 4960 |
return |
| 4961 |
} |
| 4962 |
} |
| 4963 |
// Capture consumer leader here. |
| 4964 |
isConsumerLeader := cc.isConsumerLeader(acc.Name, streamName, consumerName) |
| 4965 |
// Also capture if we think there is no meta leader. |
| 4966 |
var isLeaderLess bool |
| 4967 |
if !isLeader { |
| 4968 |
isLeaderLess = groupLeaderless && time.Since(groupCreated) > lostQuorumIntervalDefault |
| 4969 |
} |
| 4970 |
js.mu.RUnlock() |
| 4971 |
|
| 4972 |
if isLeader && ca == nil { |
| 4973 |
// We can't find the consumer, so mimic what would be the errors below. |
| 4974 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 4975 |
if doErr { |
| 4976 |
resp.Error = NewJSNotEnabledForAccountError() |
| 4977 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4978 |
} |
| 4979 |
return |
| 4980 |
} |
| 4981 |
if sa == nil { |
| 4982 |
resp.Error = NewJSStreamNotFoundError() |
| 4983 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4984 |
return |
| 4985 |
} |
| 4986 |
// If we are here the consumer is not present. |
| 4987 |
resp.Error = NewJSConsumerNotFoundError() |
| 4988 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 4989 |
return |
| 4990 |
} else if ca == nil { |
| 4991 |
if isLeaderLess { |
| 4992 |
resp.Error = NewJSClusterNotAvailError() |
| 4993 |
// Delaying an error response gives the leader a chance to respond before us |
| 4994 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 4995 |
} |
| 4996 |
return |
| 4997 |
} else if isLeader && offline { |
| 4998 |
resp.Error = NewJSConsumerOfflineError() |
| 4999 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 5000 |
return |
| 5001 |
} |
| 5002 |
|
| 5003 |
// Check to see if we are a member of the group and if the group has no leader. |
| 5004 |
if isMember && js.isGroupLeaderless(ca.Group) { |
| 5005 |
resp.Error = NewJSClusterNotAvailError() |
| 5006 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5007 |
return |
| 5008 |
} |
| 5009 |
|
| 5010 |
// We have the consumer assigned and a leader, so only the consumer leader should answer. |
| 5011 |
if !isConsumerLeader { |
| 5012 |
if isLeaderLess { |
| 5013 |
resp.Error = NewJSClusterNotAvailError() |
| 5014 |
// Delaying an error response gives the leader a chance to respond before us |
| 5015 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), ca.Group, errRespDelay) |
| 5016 |
return |
| 5017 |
} |
| 5018 |
|
| 5019 |
var node RaftNode |
| 5020 |
var leaderNotPartOfGroup bool |
| 5021 |
|
| 5022 |
// We have a consumer assignment. |
| 5023 |
if isMember { |
| 5024 |
js.mu.RLock() |
| 5025 |
if rg != nil && rg.node != nil { |
| 5026 |
node = rg.node |
| 5027 |
if gl := node.GroupLeader(); gl != _EMPTY_ && !rg.isMember(gl) { |
| 5028 |
leaderNotPartOfGroup = true |
| 5029 |
} |
| 5030 |
} |
| 5031 |
js.mu.RUnlock() |
| 5032 |
} |
| 5033 |
|
| 5034 |
// Check if we should ignore all together. |
| 5035 |
if node == nil { |
| 5036 |
// We have been assigned but have not created a node yet. If we are a member return |
| 5037 |
// our config and defaults for state and no cluster info. |
| 5038 |
if isMember { |
| 5039 |
// Since we access consumerAssignment, need js lock. |
| 5040 |
js.mu.RLock() |
| 5041 |
resp.ConsumerInfo = &ConsumerInfo{ |
| 5042 |
Stream: ca.Stream, |
| 5043 |
Name: ca.Name, |
| 5044 |
Created: ca.Created, |
| 5045 |
Config: setDynamicConsumerMetadata(ca.Config), |
| 5046 |
TimeStamp: time.Now().UTC(), |
| 5047 |
} |
| 5048 |
b := s.jsonResponse(resp) |
| 5049 |
js.mu.RUnlock() |
| 5050 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), b) |
| 5051 |
} |
| 5052 |
return |
| 5053 |
} |
| 5054 |
// If we are a member and we have a group leader or we had a previous leader consider bailing out. |
| 5055 |
bail := !node.Leaderless() || node.HadPreviousLeader() || rg == nil |
| 5056 |
if !bail { |
| 5057 |
js.mu.RLock() |
| 5058 |
bail = rg.Preferred != ourID || (rg.node != nil && time.Since(rg.node.Created()) > lostQuorumIntervalDefault) |
| 5059 |
js.mu.RUnlock() |
| 5060 |
} |
| 5061 |
if bail { |
| 5062 |
if leaderNotPartOfGroup { |
| 5063 |
resp.Error = NewJSConsumerOfflineError() |
| 5064 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 5065 |
} |
| 5066 |
return |
| 5067 |
} |
| 5068 |
// If we are here we are a member and this is just a new consumer that does not have a (preferred) leader yet. |
| 5069 |
// Will fall through and return what we have. All consumers can respond but this should be very rare |
| 5070 |
// but makes more sense to clients when they try to create, get a consumer exists, and then do consumer info. |
| 5071 |
} |
| 5072 |
} |
| 5073 |
|
| 5074 |
if errorOnRequiredApiLevel(hdr) { |
| 5075 |
resp.Error = NewJSRequiredApiLevelError() |
| 5076 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5077 |
return |
| 5078 |
} |
| 5079 |
|
| 5080 |
if !acc.JetStreamEnabled() { |
| 5081 |
resp.Error = NewJSNotEnabledForAccountError() |
| 5082 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5083 |
return |
| 5084 |
} |
| 5085 |
|
| 5086 |
mset, err := acc.lookupStream(streamName) |
| 5087 |
if err != nil { |
| 5088 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 5089 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5090 |
return |
| 5091 |
} |
| 5092 |
|
| 5093 |
obs := mset.lookupConsumer(consumerName) |
| 5094 |
if obs == nil { |
| 5095 |
resp.Error = NewJSConsumerNotFoundError() |
| 5096 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5097 |
return |
| 5098 |
} |
| 5099 |
|
| 5100 |
if obs.offlineReason != _EMPTY_ { |
| 5101 |
resp.Error = NewJSConsumerOfflineReasonError(errors.New(obs.offlineReason)) |
| 5102 |
s.sendDelayedAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp), nil, errRespDelay) |
| 5103 |
return |
| 5104 |
} |
| 5105 |
|
| 5106 |
if resp.ConsumerInfo = setDynamicConsumerInfoMetadata(obs.info()); resp.ConsumerInfo == nil { |
| 5107 |
// This consumer returned nil which means it's closed. Respond with not found. |
| 5108 |
resp.Error = NewJSConsumerNotFoundError() |
| 5109 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5110 |
return |
| 5111 |
} |
| 5112 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 5113 |
} |
| 5114 |
|
| 5115 |
// Request to delete an Consumer. |
| 5116 |
func (s *Server) jsConsumerDeleteRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 5117 |
if c == nil || !s.JetStreamEnabled() { |
| 5118 |
return |
| 5119 |
} |
| 5120 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 5121 |
if err != nil { |
| 5122 |
s.Warnf(badAPIRequestT, msg) |
| 5123 |
return |
| 5124 |
} |
| 5125 |
|
| 5126 |
var resp = JSApiConsumerDeleteResponse{ApiResponse: ApiResponse{Type: JSApiConsumerDeleteResponseType}} |
| 5127 |
|
| 5128 |
// Determine if we should proceed here when we are in clustered mode. |
| 5129 |
if s.JetStreamIsClustered() { |
| 5130 |
js, cc := s.getJetStreamCluster() |
| 5131 |
if js == nil || cc == nil { |
| 5132 |
return |
| 5133 |
} |
| 5134 |
if js.isLeaderless() { |
| 5135 |
resp.Error = NewJSClusterNotAvailError() |
| 5136 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5137 |
return |
| 5138 |
} |
| 5139 |
// Make sure we are meta leader. |
| 5140 |
if !s.JetStreamIsLeader() { |
| 5141 |
return |
| 5142 |
} |
| 5143 |
} |
| 5144 |
|
| 5145 |
if errorOnRequiredApiLevel(hdr) { |
| 5146 |
resp.Error = NewJSRequiredApiLevelError() |
| 5147 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5148 |
return |
| 5149 |
} |
| 5150 |
|
| 5151 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 5152 |
if doErr { |
| 5153 |
resp.Error = NewJSNotEnabledForAccountError() |
| 5154 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5155 |
} |
| 5156 |
return |
| 5157 |
} |
| 5158 |
if !isEmptyRequest(msg) { |
| 5159 |
resp.Error = NewJSNotEmptyRequestError() |
| 5160 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5161 |
return |
| 5162 |
} |
| 5163 |
stream := streamNameFromSubject(subject) |
| 5164 |
consumer := consumerNameFromSubject(subject) |
| 5165 |
|
| 5166 |
if s.JetStreamIsClustered() { |
| 5167 |
s.jsClusteredConsumerDeleteRequest(ci, acc, stream, consumer, subject, reply, rmsg) |
| 5168 |
return |
| 5169 |
} |
| 5170 |
|
| 5171 |
mset, err := acc.lookupStream(stream) |
| 5172 |
if err != nil { |
| 5173 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 5174 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5175 |
return |
| 5176 |
} |
| 5177 |
|
| 5178 |
obs := mset.lookupConsumer(consumer) |
| 5179 |
if obs == nil { |
| 5180 |
resp.Error = NewJSConsumerNotFoundError() |
| 5181 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5182 |
return |
| 5183 |
} |
| 5184 |
if err := obs.delete(); err != nil { |
| 5185 |
resp.Error = NewJSStreamGeneralError(err, Unless(err)) |
| 5186 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5187 |
return |
| 5188 |
} |
| 5189 |
resp.Success = true |
| 5190 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 5191 |
} |
| 5192 |
|
| 5193 |
// Request to pause or unpause a Consumer. |
| 5194 |
func (s *Server) jsConsumerPauseRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) { |
| 5195 |
if c == nil || !s.JetStreamEnabled() { |
| 5196 |
return |
| 5197 |
} |
| 5198 |
ci, acc, hdr, msg, err := s.getRequestInfo(c, rmsg) |
| 5199 |
if err != nil { |
| 5200 |
s.Warnf(badAPIRequestT, msg) |
| 5201 |
return |
| 5202 |
} |
| 5203 |
|
| 5204 |
var req JSApiConsumerPauseRequest |
| 5205 |
var resp = JSApiConsumerPauseResponse{ApiResponse: ApiResponse{Type: JSApiConsumerPauseResponseType}} |
| 5206 |
|
| 5207 |
if isJSONObjectOrArray(msg) { |
| 5208 |
if err := s.unmarshalRequest(c, acc, subject, msg, &req); err != nil { |
| 5209 |
resp.Error = NewJSInvalidJSONError(err) |
| 5210 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5211 |
return |
| 5212 |
} |
| 5213 |
} |
| 5214 |
|
| 5215 |
// Determine if we should proceed here when we are in clustered mode. |
| 5216 |
isClustered := s.JetStreamIsClustered() |
| 5217 |
js, cc := s.getJetStreamCluster() |
| 5218 |
if isClustered { |
| 5219 |
if js == nil || cc == nil { |
| 5220 |
return |
| 5221 |
} |
| 5222 |
if js.isLeaderless() { |
| 5223 |
resp.Error = NewJSClusterNotAvailError() |
| 5224 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5225 |
return |
| 5226 |
} |
| 5227 |
// Make sure we are meta leader. |
| 5228 |
if !s.JetStreamIsLeader() { |
| 5229 |
return |
| 5230 |
} |
| 5231 |
} |
| 5232 |
|
| 5233 |
if errorOnRequiredApiLevel(hdr) { |
| 5234 |
resp.Error = NewJSRequiredApiLevelError() |
| 5235 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5236 |
return |
| 5237 |
} |
| 5238 |
|
| 5239 |
if hasJS, doErr := acc.checkJetStream(); !hasJS { |
| 5240 |
if doErr { |
| 5241 |
resp.Error = NewJSNotEnabledForAccountError() |
| 5242 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5243 |
} |
| 5244 |
return |
| 5245 |
} |
| 5246 |
|
| 5247 |
stream := streamNameFromSubject(subject) |
| 5248 |
consumer := consumerNameFromSubject(subject) |
| 5249 |
|
| 5250 |
if isClustered { |
| 5251 |
js.mu.Lock() |
| 5252 |
sa := js.streamAssignment(acc.Name, stream) |
| 5253 |
if sa == nil { |
| 5254 |
js.mu.Unlock() |
| 5255 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 5256 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5257 |
return |
| 5258 |
} |
| 5259 |
if sa.unsupported != nil { |
| 5260 |
js.mu.Unlock() |
| 5261 |
// Just let the request time out. |
| 5262 |
return |
| 5263 |
} |
| 5264 |
|
| 5265 |
ca, ok := sa.consumers[consumer] |
| 5266 |
if !ok || ca == nil { |
| 5267 |
js.mu.Unlock() |
| 5268 |
resp.Error = NewJSConsumerNotFoundError() |
| 5269 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5270 |
return |
| 5271 |
} |
| 5272 |
if ca.unsupported != nil { |
| 5273 |
js.mu.Unlock() |
| 5274 |
// Just let the request time out. |
| 5275 |
return |
| 5276 |
} |
| 5277 |
|
| 5278 |
nca := ca.clone() |
| 5279 |
// We need a copy to prevent concurrent reads/writes. |
| 5280 |
ncfg := *ca.Config |
| 5281 |
ncfg.Metadata = maps.Clone(ncfg.Metadata) |
| 5282 |
nca.Config = &ncfg |
| 5283 |
meta := cc.meta |
| 5284 |
pauseUTC := req.PauseUntil.UTC() |
| 5285 |
if !pauseUTC.IsZero() { |
| 5286 |
nca.Config.PauseUntil = &pauseUTC |
| 5287 |
} else { |
| 5288 |
nca.Config.PauseUntil = nil |
| 5289 |
} |
| 5290 |
|
| 5291 |
// Update asset version metadata due to updating pause/resume. |
| 5292 |
// Only PauseUntil is updated above, so reuse config for both. |
| 5293 |
setStaticConsumerMetadata(nca.Config) |
| 5294 |
|
| 5295 |
eca := encodeAddConsumerAssignment(nca) |
| 5296 |
if err = meta.Propose(cc.term, eca); err != nil { |
| 5297 |
js.mu.Unlock() |
| 5298 |
return |
| 5299 |
} |
| 5300 |
cc.trackInflightConsumerProposal(acc.Name, stream, nca, false) |
| 5301 |
js.mu.Unlock() |
| 5302 |
|
| 5303 |
resp.PauseUntil = pauseUTC |
| 5304 |
if resp.Paused = time.Now().Before(pauseUTC); resp.Paused { |
| 5305 |
resp.PauseRemaining = time.Until(pauseUTC) |
| 5306 |
} |
| 5307 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 5308 |
return |
| 5309 |
} |
| 5310 |
|
| 5311 |
mset, err := acc.lookupStream(stream) |
| 5312 |
if err != nil { |
| 5313 |
resp.Error = NewJSStreamNotFoundError(Unless(err)) |
| 5314 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5315 |
return |
| 5316 |
} |
| 5317 |
if mset.offlineReason != _EMPTY_ { |
| 5318 |
// Just let the request time out. |
| 5319 |
return |
| 5320 |
} |
| 5321 |
|
| 5322 |
obs := mset.lookupConsumer(consumer) |
| 5323 |
if obs == nil { |
| 5324 |
resp.Error = NewJSConsumerNotFoundError() |
| 5325 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5326 |
return |
| 5327 |
} |
| 5328 |
if obs.offlineReason != _EMPTY_ { |
| 5329 |
// Just let the request time out. |
| 5330 |
return |
| 5331 |
} |
| 5332 |
|
| 5333 |
// We're only holding the read lock and release below, |
| 5334 |
// we need a copy to prevent concurrent reads/writes. |
| 5335 |
obs.mu.RLock() |
| 5336 |
ncfg := obs.cfg |
| 5337 |
ncfg.Metadata = maps.Clone(ncfg.Metadata) |
| 5338 |
obs.mu.RUnlock() |
| 5339 |
|
| 5340 |
pauseUTC := req.PauseUntil.UTC() |
| 5341 |
if !pauseUTC.IsZero() { |
| 5342 |
ncfg.PauseUntil = &pauseUTC |
| 5343 |
} else { |
| 5344 |
ncfg.PauseUntil = nil |
| 5345 |
} |
| 5346 |
|
| 5347 |
// Update asset version metadata due to updating pause/resume. |
| 5348 |
setStaticConsumerMetadata(&ncfg) |
| 5349 |
|
| 5350 |
if err := obs.updateConfig(&ncfg); err != nil { |
| 5351 |
// The only type of error that should be returned here is from o.store, |
| 5352 |
// so use a store failed error type. |
| 5353 |
resp.Error = NewJSConsumerStoreFailedError(err) |
| 5354 |
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp)) |
| 5355 |
return |
| 5356 |
} |
| 5357 |
|
| 5358 |
resp.PauseUntil = pauseUTC |
| 5359 |
if resp.Paused = time.Now().Before(pauseUTC); resp.Paused { |
| 5360 |
resp.PauseRemaining = time.Until(pauseUTC) |
| 5361 |
} |
| 5362 |
s.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp)) |
| 5363 |
} |
| 5364 |
|
| 5365 |
// sendJetStreamAPIAuditAdvisory will send the audit event for a given event. |
| 5366 |
func (s *Server) sendJetStreamAPIAuditAdvisory(ci *ClientInfo, acc *Account, subject, request, response string) { |
| 5367 |
s.publishAdvisory(acc, JSAuditAdvisory, JSAPIAudit{ |
| 5368 |
TypedEvent: TypedEvent{ |
| 5369 |
Type: JSAPIAuditType, |
| 5370 |
ID: nuid.Next(), |
| 5371 |
Time: time.Now().UTC(), |
| 5372 |
}, |
| 5373 |
Server: s.Name(), |
| 5374 |
Client: ci.forAdvisory(), |
| 5375 |
Subject: subject, |
| 5376 |
Request: request, |
| 5377 |
Response: response, |
| 5378 |
Domain: s.getOpts().JetStreamDomain, |
| 5379 |
}) |
| 5380 |
} |